gpt4 book ai didi

java - Spring 事务传播 - Service 与 DAO

转载 作者:行者123 更新时间:2023-12-01 10:54:44 25 4
gpt4 key购买 nike

我有一个如下所示的服务类:

@Service("MyService")
public class MyService {
@Autowired
MyDao dao;

public void process() {
getFromDao();
// getMoreFromDao();
// process();
// if all good, then
doStuff();
}

public void getFromDao() {
// do some stuff
dao.getData();
}

@Transactional(transactionManager="simpleDatasourceTxMgr", propagation=Propagation.REQUIRED)
public void doStuff() {
dao.saveData(1);
dao.saveData(2);
dao.saveData(3);
}
}

调用的 DAO 是:

@Repository
public class MyDao {

@Autowired
@Qualifier("myjdbcTemplate")
NamedParameterJdbcTemplate jdbcTemplate;

public void saveData(obj a) {
jdbcTemplate.execute("Query", ...);
}
}

我希望服务类中的 doStuff() 方法在事务中运行,并在 saveData() 方法中出现异常时回滚所有内容。但这不是在事务中运行。

如果我将 @Transaction 添加到 DAO 方法,看起来它会在单独的事务中运行。这是正确的吗?

更新:我已向我的服务添加了 process() 方法,并调用 getFromDao()doStuff() 来自process()process() 从 Controller 调用。所以看起来如果我创建服务类@Transactional,那么一切都会在事务中执行。但我不希望 getFromDao() 在事务中执行。

我们只使用 JDBC,不使用 Hibernate。

最佳答案

You can place the @Transactional annotation before an interface definition, a method on an interface, a class definition, or a public method on a class. However, the mere presence of the @Transactional annotation is not enough to activate the transactional behavior. The @Transactional annotation is simply metadata that can be consumed by some runtime infrastructure that is @Transactional-aware and that can use the metadata to configure the appropriate beans with transactional behavior. In the preceding example, the element switches on the transactional behavior.

或者,如果您想要注释,可以使用

启用它

It is not sufficient to tell you simply to annotate your classes with the @Transactional annotation, add @EnableTransactionManagement to your configuration, and then expect you to understand how it all works. This section explains the inner workings of the Spring Framework’s declarative transaction infrastructure in the event of transaction-related issues.

http://docs.spring.io/spring/docs/current/spring-framework-reference/html/transaction.html

关于java - Spring 事务传播 - Service 与 DAO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33677993/

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