Hibernate Criteria With Property Not In (Subquery)

ぃ、小莉子 提交于 2019-11-27 06:32:30

问题


I want to execute query something like

Select id, name from information where name not in (select firstname from contact where id  = 1)

Information
Id Name
1  Test

Contact
id firstname
1  name
2  Test

If I am using neProperty() function, it will returns records as name != Test.

How can I implement using hibernate criteria?

Thanks


回答1:


Create a select-all criteria:

Criteria cr = session.createCriteria(Your.class); 
List list = cr.list(); 

Then you can add you restriction to it, i.e. where column 1=8 etc like this:

cr.add(Restrictions.eq("YourCondition", YourCondition));

Finally, you can provide the not in clause like this:

cr.add(Restrictions.not(Restrictions.in("YourNotInCondition", YourNotInCondition)));



回答2:


You could use DetachedCriteria to build the subquery.

// This corresponds to (select firstname from contact where id  = 1)
DetachedCriteria subquery = DetachedCriteria.forClass(Contact.class)
    .add(Restrictions.eq("id", 1))
    .setProjection(Projections.property("name"))

// This corresponds to (select information where name not in (subquery))
ICriteria criteria = session
    .createCriteria(Information.class)
    .add(Subqueries.notIn("name", subquery));

Instead of using a subquery, you can just load the contact using session.get, with a chance to hit the cache:

Contact contact = session.Get<Contact>(1);

ICriteria criteria = session
    .createCriteria(Information.class)
    .add(Property.ne("name", contact.getName()));

Disclamer: I'm a) not a java programmer and b) may have made mistakes so it probably does not compile. The code is more to roughly show the idea and is hopefully helpful anyway.



来源:https://stackoverflow.com/questions/12635404/hibernate-criteria-with-property-not-in-subquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!