3

I'm trying to delete all database entries for a Spring Roo entity. When I look at *_Roo_Entity.aj it seems as if there is no "delete all" method. I tried to implement it myself (Licences is the name of the Roo entity. Don't mind the naming. It was reverese engineered from a database and may be changed later):

public static int Licences.deleteAll() {
    return entityManager().createQuery("delete from Licences o").executeUpdate();
}

It compiles just fine but when I call Licences.deleteAll() I get the following exception:

org.springframework.dao.InvalidDataAccessApiUsageException: Executing an update/delete query; 
nested exception is javax.persistence.TransactionRequiredException: Executing an update/delete query (NativeException)

Adding @Transactional doesn't make a difference.

What am I missing here?

Is this approach completely wrong and I need to implement it like this:

    public static void Licences.deleteAll() {
        for (Licences licence : findAllLicenceses()) {
            licence.remove();
        }
    }

This works, but is JPA smart enough to translate this into a delete from licences query or will it create n queries?

4

3 回答 3

6

@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

再见

于 2011-06-21T16:56:48.947 回答
2
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();
}
于 2011-11-09T09:20:50.840 回答
2

JPA 没有删除所有功能。(即使没有 JQL!)

至少只有三种方式:

顺便说一句:您正在使用 AspectJ 来附加您的删除方法。- 你可以这样做(即使我不知道,为什么不直接将静态方法添加到Entity类中),但你不能触摸Roo生成的aj文件!

于 2011-04-14T08:46:22.850 回答