Spring的JdbcTemplate和Transactions [英] Spring's JdbcTemplate and Transactions

查看:92
本文介绍了Spring的JdbcTemplate和Transactions的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用JdbcTemplate时,是否需要显式配置事务?

When using JdbcTemplate, do I need to explicitly configure transactions?

我的代码布局如下所示:

My code layout looks like the following:

我将有一个UserDao将被注入我的UserService,然后我的控制器将调用我的UserService中的方法。

I will have a UserDao that will be injected into my UserService, and then my Controllers will make calls on methods in my UserService.

我想保留一些东西尽可能简单的事务,我不需要多个数据库调用来跨越事务。

I want to keep things as simple as possible transaction wise, and I don't need multiple database calls to span a transaction.

默认情况下,我是否必须在配置文件中执行任何操作或使用一个 @Transaction 注释在哪里?

By default, do I have to do anything in my configuration file or use a @Transaction annotation anywhere?

现在在我的控制器中说我需要在我的userService和accountService上进行2次调用,我可以以某种方式明确地将其包装在交易中吗?

Now say in my controller I need to make 2 calls on my userService and accountService, could I explicitly wrap it in a transaction somehow?

userService.updateUser(user);
accountService.updateXXX(...);


推荐答案

是, JdbcTemplate 不能替代事务管理。您仍然可以从数据库事务中受益,因此 userService.updateUser 将在数据库事务中运行,但如果 accountService.updateXXX 失败, userService.updateUser 回滚。

Yes, JdbcTemplate is not a substitute for transaction management. You still benefit from database transactions, so userService.updateUser will operate in a database transaction, but if accountService.updateXXX fails, userService.updateUser will not rollback.

如果您不想使用AOP,可以使用 TransactionTemplate 。请参阅程序化事务管理< Spring参考文档中的/ a> 。

If you don't want to use AOP, you can use TransactionTemplate instead. See programmatic transaction management in the Spring Reference Documentation.

我之前看到的一种模式是MVC控制器类调用业务服务,它封装了操作。然后可以注释业务类的方法 @Transactional

One pattern I've seen before is for the MVC controller class to invoke a business service, which encapsulates the operation. The method of the business class could then be annotated @Transactional.

这篇关于Spring的JdbcTemplate和Transactions的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆