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

时间:2021-10-08 13:00:01

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来做到这一点,但我必须使用标准。

How i can do this?

我怎么能这样做?

Thanks.

谢谢。

2 个解决方案

#1


1  

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:

这种方法在性能方面非常慢,但IFF你真的必须使用它:

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

     entityManager.remove(doomed);
 }

#2


1  

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'));

#1


1  

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:

这种方法在性能方面非常慢,但IFF你真的必须使用它:

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

     entityManager.remove(doomed);
 }

#2


1  

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'));