我有两个名为Expert and Technology的课程,一个专家可以提供多种技术,一项技术由几位专家制作。添加,更新技术独立于专家类。从专家中删除maitrised技术只删除相关关系。
Class Expert{
Long id; // getter and setter
String name; // getter and setter;
Set<Technology> technos; // getter and setter
}
Technology{
Long id; // gettter and setter
String name; //getter and setter
}
hibernate映射中反映的两个类之间的关系是
<class name="Expert">
<!-- put the declaration for id and name -->
<set name="technos" table="EXPERT_TECHNO" cascade="delete-orphan">
<key column="id_expert"/>
<many-to-many column="id_techno" class = "Technology"/>
</set>
</class>
<class name="Technology">
<!-- put declaration for id and name-->
</class>
现在我有一个技术实例,我想找到所有专门负责技术的专家,那么如何使用hibernate critera来获得结果集?或者使用createQuery获取结果集的最简单方法。
我不熟悉hibernate critera方法,所以我呼唤你的帮助!
进一步的问题:
当我想从专家那里删除一项技术时,我想要的只是删除表“EXPET_TECHNO”中的一行,但是我所拥有的是expert.getTechnos.remove(techno),将从中移除技术这是我不想要的桌子!
答案 0 :(得分:2)
首先,解决此问题的最简单方法是使ManyToMany关联双向。你只需要做
Set<Expert> experts = technology.getExperts();
现在,如果它不是一个选项,那么HQL对于这样的查询来说比Criteria更容易,这个查询不是动态组合的。查询就像
一样简单select expert from Expert expert
inner join expert.technos techno
where techno.id = :technoId
如果您真的想要使用Criteria执行此操作,则需要执行以下操作:
Criteria c = session.createCriteria(Expert.class, "expert");
c.createAlias("expert.technos", "techno");
c.add(Restrictions.eq("techno.id", technoId));
您可以通过阅读Hibernate documentation来自己找到并学到很多其他内容。