简体   繁体   English

Hibernate 条件限制对多个条件

[英]Hibernate criteria restriction on multiple criterias

I am writing a Criteria query.我正在编写一个标准查询。 My query is on multiple criterias corresponding to tables property and user.我的查询针对与表属性和用户相对应的多个条件。 It returns the result if prop is 12 or 13 no matter who the user is OR if prop is NULL then user must be loggedInUser.无论用户是谁,如果 prop 为 12 或 13,它都会返回结果,或者如果 prop 为 NULL,则用户必须是 loginInUser。 The Sql query has where condition as follows which returns 4 rows Sql 查询的 where 条件如下,返回 4 行

where (property.PROP in (12,13) or (property.PROP is null
                 and user.loggedInUser = 'XYZ'))

My criteria我的标准

Criteria userQuery = session.createCriteria(User.class);
Criteria propertyQuery = userQuery .createCriteria("property");

  Criterion crt = (Criterion) userQuery.add(Restrictions.eq("loggedInUser", userId));

propertyQuery.add(
            Restrictions.or( 
                 Restrictions.in("prop",propList),
                    Restrictions.and(Restrictions.isNull("prop"),crt)
                            )
                 );

My issue is that Restrictions.and(criterion,criterion) takes two criterion as parameter.我的问题是 Restrictions.and(criterion,criterion) 将两个标准作为参数。 However, the second criterion 'crt' on userQuery is not valid when type casted (Criterion).但是,当类型转换(Criterion)时,userQuery 上的第二个条件“crt”无效。 Hibernate will give error.休眠会报错。 How can I achieve this functionality in Criteria.如何在 Criteria 中实现此功能。 or how to write criteria Restrictions.and(Restrictions.isNull("prop") , userQuery.add(Restrictions.eq("loggedInUser", userId)))或如何编写标准Restrictions.and(Restrictions.isNull("prop") , userQuery.add(Restrictions.eq("loggedInUser", userId)))

Use Joins using hibernate criteria as below example code:使用使用休眠条件的连接作为以下示例代码:

 List cats = session.createCriteria(Cat.class)
     .createAlias("kittens", "kit")
     .add( Restrictions.like("kit.name", "Iz%") )
     .list();

Note: The code above is just an example of how to use Join in hibernate criteria.注意:上面的代码只是如何在休眠条件中使用 Join 的示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM