gpt4 book ai didi

java - 删除在 hibernate 中不起作用

转载 作者:行者123 更新时间:2023-11-30 22:24:17 25 4
gpt4 key购买 nike

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

unexpected token: ( near line 1, column 104

第二个 select 子句出错。

查询是:

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

有人知道为什么会这样以及如何解决吗?

最佳答案

您的别名'' 从未被使用过。简单地试试这个:)

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

如果您正在处理 Hibernate,请尝试使用 Hibernate 查询语言 (HQL)。例如,我们使用HQL来删除实体更灵活,比如删除价格大于指定数量的产品。

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");
}

您还可以使用类 HibernateTemplate 中的方法 execute(HibernateCallback action)。它可能看起来像这样:

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

恕我直言,此解决方案效率不高,因为您必须先阅读所有条目,然后才能删除它们。更重要的是,您必须单独删除每个条目,这是非常低效的。

关于java - 删除在 hibernate 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35744887/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com