Java Hibernate Restcrition Criteria 或与 DetachedCritera

Java Hibernate Restcrition Criteria OR with DetachedCritera

Criteria criteria = session.createCriteria(TableA.class)
        .add(Subqueries.propertyNotIn("id_a", DetachedCriteria.forClass(TableB.class)
        .createAlias("id_a_from_tableB", "b")
        setProjection(Property.forName("b.id_a"))));

我用它从 TableA 中获取 id_a if id_a 不在 TableB 中。我还需要 id_a 如果在 TableB 但字段 "message" 不为空。

我觉得这个post可以

with criteria I think hibernate does not support UNION ALL but you can use two criteria queries to get the expected result:

Criteria cr1 = session.createCriteria(Suppliers.class);
 cr1.setProjection(Projections.projectionList()
    .add( Projections.property("supplier_id"), "supplier_id" )
 );
List results1 = cr1.list();

Criteria cr2 = session.createCriteria(Orders.class);
 cr2.setProjection(Projections.projectionList()
    .add( Projections.property("supplier_id"), "supplier_id" )
 );
List results2 = cr2.list();

results1.add(results2); 

List unionAllList =  results1; //this is the expected result.

例如,如果消息不为空,您可以在从 TableB 获取消息时添加新条件,然后加入两个 Java 集合:

Criteria criteria1 = session.createCriteria(TableB.class)
.add( Restrictions.isNotNull("message") 

P.S. 或者我建议使用 JPA2.1(第 6 章)中的 Criteria API 而不是 hibernate Criteria,因为它看起来像简单 SQL 并且此解决方案更为普遍。