属性不在的Hibernate标准(子查询)

Vin*_*ati 3 hibernate subquery hibernate-criteria

我想执行类似的查询

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
Run Code Online (Sandbox Code Playgroud)

如果我使用neProperty()函数,它将返回记录为 name != Test.

如何使用hibernate标准实现?

谢谢

Ste*_*ger 12

您可以使用DetachedCriteria来构建子查询.

// 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));
Run Code Online (Sandbox Code Playgroud)

您可以使用session.get加载联系人,而不是使用子查询,有机会点击缓存:

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

ICriteria criteria = session
    .createCriteria(Information.class)
    .add(Property.ne("name", contact.getName()));
Run Code Online (Sandbox Code Playgroud)

Disclamer:我是a)不是java程序员而且b)可能犯了错误,所以它可能无法编译.代码更粗略地展示了这个想法,无论如何都希望有用.