问题描述
|
我正在尝试删除Spring Roo实体的所有数据库条目。当我查看“ 0”时,似乎没有“全部删除”方法。我尝试自己实现它(ѭ1是Roo实体的名称。不要介意命名。它是通过数据库进行reverese设计的,以后可能会更改):
public static int Licences.deleteall() {
return entityManager().createquery(\"delete from Licences o\").executeUpdate();
}
它可以正常编译,但是当我调用Licences.deleteall()
时,出现以下异常:
org.springframework.dao.InvalidDataAccessApiUsageException: Executing an update/delete query;
nested exception is javax.persistence.TransactionrequiredException: Executing an update/delete query (NativeException)
加ѭ5没什么区别。
我在这里想念什么?
这种方法是完全错误的,我需要这样实现吗:
public static void Licences.deleteall() {
for (Licences licence : findAllLicenceses()) {
licence.remove();
}
}
这是可行的,但是JPA是否足够聪明,可以将其转换为delete from licences
查询,还是会创建n
查询?
解决方法
@Transactional在静态函数上不起作用
更改
public static int Licences.deleteAll() {
return entityManager().createQuery(\"delete from Licences o\").executeUpdate();
}
至
public int Licences.deleteAll() {
return entityManager().createQuery(\"delete from Licences o\").executeUpdate();
}
https://jira.springsource.org/browse/SPR-5999
再见
,JPA没有删除所有功能。 (即使不是JQL!)
至少只有三种方式:
像你一样循环
JPQL查询请参阅:JPQL参考:10.2.9。 JPQL批量更新和删除
本机SQL查询,但这将导致实体管理器缓存很多问题!
顺便说一句:它表明您正在使用AspectJ附加删除方法。 -您可以执行此操作(即使我不知道,为什么不直接将静态方法添加到Entity类),但也不能触摸Roo生成的aj文件!
,public static int Licences.deleteAll() {
return new Licences().deleteAllTransactional();
}
@Transactional
private int Licences.deleteAllTransactional() {
if (this.entityManager == null) this.entityManager = entityManager();
return this.entityManager.createQuery(\"delete from Licences o\").executeUpdate();
}