您应该将@Transactional放在DAO类和/或它们的方法中,还是更好地注释使用DAO对象调用的服务类?或者对两个“层”都加注释有意义吗?


当前回答

用于数据库级别的事务

大多数情况下,我在DAO的方法级别上使用@Transactional,所以配置可以专门用于一个方法/使用默认值(必需的)

DAO获取数据的方法(select ..)-不需要 @事务性这可能会导致一些开销,因为 事务拦截器/和需要执行的AOP代理 好。 DAO的插入/更新方法将获得@Transactional

非常好的博客

应用级别: 我正在使用事务性业务逻辑,我希望能够在发生意外错误的情况下回滚

@Transactional(rollbackFor={MyApplicationException.class})
public void myMethod(){

    try {    
        //service logic here     
    } catch(Throwable e) {

        log.error(e)
        throw new MyApplicationException(..);
    }
}

其他回答

事务注释应该放在所有不可分割的操作周围。

例如,你的呼叫是“change password”。它由两个操作组成

修改密码。 审计变更。 通过电子邮件通知客户端密码已更改。

那么在上面,如果审计失败,那么修改密码也应该失败吗?如果是这样,那么事务应该在1和2左右(因此在服务层)。如果电子邮件失败了(可能应该有某种故障安全措施,这样它就不会失败),那么它是否应该回滚更改密码和审计?

在决定将@Transactional放在哪里时,您需要询问这些问题。

传统Spring体系结构的正确答案是将事务语义放在服务类上,原因其他人已经描述过了。

An emerging trend in Spring is toward domain-driven design (DDD). Spring Roo exemplifies the trend nicely. The idea is to make the domain object POJOs a lot richer than they are on typical Spring architectures (usually they are anemic), and in particular to put transaction and persistence semantics on the domain objects themselves. In cases where all that's needed is simple CRUD operations, the web controllers operate directly on the domain object POJOs (they're functioning as entities in this context), and there's no service tier. In cases where there's some kind of coordination needed between domain objects, you can have a service bean handle that, with @Transaction as per tradition. You can set the transaction propagation on the domain objects to something like REQUIRED so that the domain objects use any existing transactions, such as transactions that were started at the service bean.

从技术上讲,这种技术使用了AspectJ和<context:spring-configured />。Roo使用AspectJ类型间定义将实体语义(事务和持久性)与领域对象(基本上是字段和业务方法)分离开来。

或者对两个“层”都加注释有意义吗?-同时标注服务层和dao层不是很有意义吗-如果你想确保dao方法总是从服务层调用(传播),并且在dao中传播是“强制的”。这将为DAO方法从UI层(或控制器)调用提供一些限制。此外——特别是在对DAO层进行单元测试时——对DAO进行注释还将确保对其事务功能进行测试。

最好把它放在服务层!这在我昨天看到的一篇文章中有清楚的解释!这是你可以查看的链接!

用于数据库级别的事务

大多数情况下,我在DAO的方法级别上使用@Transactional,所以配置可以专门用于一个方法/使用默认值(必需的)

DAO获取数据的方法(select ..)-不需要 @事务性这可能会导致一些开销,因为 事务拦截器/和需要执行的AOP代理 好。 DAO的插入/更新方法将获得@Transactional

非常好的博客

应用级别: 我正在使用事务性业务逻辑,我希望能够在发生意外错误的情况下回滚

@Transactional(rollbackFor={MyApplicationException.class})
public void myMethod(){

    try {    
        //service logic here     
    } catch(Throwable e) {

        log.error(e)
        throw new MyApplicationException(..);
    }
}