简体   繁体   English

如何在hibernate中使用条件执行此sql查询?

[英]How to execute this sql query using criteria in hibernate?

I have a sql query 我有一个SQL查询

delete from response where r_id in (1,2,3,4) and u_id='10';

Now I want to execute this queru using hibernate. 现在我想使用hibernate执行这个queru。

I know i can do this through createSQLQuery but I have to use criteria. 我知道我可以通过createSQLQuery来做到这createSQLQuery但我必须使用标准。

How i can do this? 我怎么能这样做?

Thanks. 谢谢。

If you have to use criteria here, you will have to fetch all the objects to Java and delete them using Java mechanisms. 如果必须在此处使用条件,则必须将所有对象提取到Java并使用Java机制删除它们。

This approach is very slow in terms of performance, but IFF you really must use it: 这种方法在性能方面非常慢,但是你真的必须使用它:

List<Response> doomedResponses =  createCriteria(Response.class).addRestriction(/* restrictions here*/).list();
for(Response doomed : doomedResponses) {

     entityManager.remove(doomed);
 }

You need to add two restrictions, one for IN, here is the java api for Restriction.in 你需要添加两个限制,一个用于IN,这里是Restriction.in的java api

static Criterion in(String propertyName, Object[] values) Apply an "in" constraint to the named property static Criterion in(String propertyName,Object [] values)对命名属性应用“in”约束

So your code should look like this 所以你的代码应该是这样的

  Criteria criteria = session.createCriteria(Yourclass.class);
// create a collection for IN values comparision and lets assume it is called CollectionofValues
       criteria.add(Restrictions.in(r_id, collectionofValues);
      criteria.add(Restriction.eq(u_id,'10'));

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

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