开发者

I want to use the id's of two different tables as the id of a third table (hibernate, java, spring)

开发者 https://www.devze.com 2023-03-23 16:21 出处:网络
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

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消