I have tables Owner
, and Species
, both entities with auto generated id Integer column.
I have third table Cat
that I want to be able retireve based on the id's of the two previous tables, so I want to do something like:
Session session = sessionFactory.getCurrentSession();
Cat cat = (Cat) session.get(Cat.class, owner.getId, species.id);
instead of
Cat cat = (Cat) se开发者_运维问答ssion.get(Cat.class, id);
What are the annotations I need on entity classes ? I am guessing it will something like this
@EmbeddedId
private CatId catId;
@ManyToOne(fetch=FetchType.EAGER)
@JoinColumn(name="ID", insertable=false, updateable=false)
private Owner owner;
@ManyToOne(fetch=FetchType.EAGER)
@JoinColumn(name="ID", insertable=false, updateable=false)
private Species species;
@ManyToOne
public Owner getOwner() {
return owner;
}
@ManyToOne
public Species getSpecies() {
return species;
}
Query:
Criteria crit = session.createCriteria(Cat.class);
crit.createAlias("owner", "ownerAlias");
crit.createAlias("species", "speciesAlias");
crit.add(Restrictions.eq("ownerAlias.id", ownerId);
crit.add(Restrictions.eq("speciesAlias.id", speciesId);
return crit.list();
Not exactly an answer, but what you want is a composite ID, and I've had enough difficulties that in my use cases I skip them, create a synthetic ID and just add uniqueness constraints on the table.
Also, the way you posted the question, it looks to me that there can be at most a single cat per (Owner,Species) tuple (e.g. an owner can't have 2 cats of the same species). If that is not correct, you will need an actual ID.
精彩评论