删除不在休眠状态下工作

时间:2016-03-02 10:43:06

标签: java mysql hibernate

我正在使用mysql。以下查询是在mysql浏览器中工作,但是当我在hibernate中使用此查询时,它在内部选择附近给出了异常,如:

unexpected token: ( near line 1, column 104

这是第二个选择条款的错误。

查询是:

delete from table 
where columnA in (
  select columnA
  from (
      select columnA
      from table
      group by columnA
      having count(*) > 1
      ) t  
)

有人知道为什么会这样,以及如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

Your alias 't' is never used. Simply try this :)

DELETE FROM table 
WHERE columnA IN (SELECT columnA
      FROM table
      GROUP BY columnA
      HAVING COUNT(*) > 1);

If you are dealing with Hibernate try to use Hibernate Query Language (HQL). For example, we use HQL to delete entities with more flexibility, such as removing products whose prices are greater than a specified amount.

Query query = session.createQuery("delete Product where price > :maxPrice");
query.setParameter("maxPrice", new Float(1000f));

int result = query.executeUpdate();

if (result > 0) {
    System.out.println("Expensive products was removed");
}

You can also use method execute(HibernateCallback action) from class HibernateTemplate. It could look like this:

final Criterion criteria;
HibernateTemplate template;
template.execute(new HibernateCallback() {
    @Override
    public Object doInHibernate(Session session) throws HibernateException, SQLException {
        List toDelete = session.createCriteria(Student.class).add(criteria).list();
        for (Object o: toDelete){
            session.delete(o);
        }
    }
});

IMHO this solution is not very efficient, because you must read all entries before you remove them. What is more you must remove each entry individually, which is very unefficient.