将MySQL查询转换为Hibernate Criteria

时间:2013-06-12 00:21:24

标签: java mysql hibernate hibernate-criteria

SELECT * FROM test.pchi new INNER JOIN rlhi old ON new_id = old.menu_id where new.name='?'

类似于:

Select * from db.employee emp INNER JOIN db.table on emp_tableID = table.id where emp.name = '?'

如果你能告诉我如何进行投影,那就太棒了......如:

Select emp.name, emp.sex, table.brand from ....

我尝试使用fetch,但我对此非常新,并且不断收到一些奇怪的错误。有人可以证明如何做到这一点?

这个怎么样?

sess.createCriteria(pchi.class)/**/
              .setFetchMode("rlhi", FetchMode.JOIN)
              .add(Restrictions.eq("new_id", "rlhi.menu_id"))
              .add(Restrictions.eq("name", "SOME INPUT"))

1 个答案:

答案 0 :(得分:1)

sess.createCriteria(Pchi.class)
              .setFetchMode("rlhi", FetchMode.JOIN) //note that rlh1 is the property name in Pchi class
              .add(Restrictions.eq("name", "SOME INPUT"));

在你的课堂上你有类似的东西

class Pchi{
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="new_id", referencedColumnName="menu_id")
private Rlhi rlhi;
}

class Rlhi{
@OneToMany(mappedBy="rlhi")
private <Set> Pchi pchis;
}

注意当您使用SET时,应覆盖equals()hashCode()方法才能正常使用