繁体   English   中英

我想将两个不同表的ID用作第三个表(Hibernate,Java,Spring)的ID

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

我有表OwnerSpecies ,这两个实体都有自动生成的ID Integer列。

我有第三个表Cat ,我希望能够根据前两个表的ID进行退休,因此我想执行以下操作:

Session session = sessionFactory.getCurrentSession();
Cat cat = (Cat) session.get(Cat.class, owner.getId, species.id);

代替

Cat cat = (Cat) session.get(Cat.class, id);

我需要在实体类上添加哪些注释? 我猜会是这样的

    @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;
}

查询:

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();

不完全是一个答案,但是您想要的是一个复合ID,并且遇到了很多困难,在我的用例中,我跳过了它们,创建了一个合成ID,只是在表上添加了唯一性约束。

另外,按照您发布问题的方式,在我看来,每个(所有者,物种)元组最多只能有一只猫(例如,一个所有者不能有2只相同种类的猫)。 如果不正确,则需要一个实际的ID。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM