事务性:控制器与服务 [英] Transactional: controller vs service

查看:31
本文介绍了事务性:控制器与服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个控制器方法 get(),它调用了一些使用数据库的服务方法.

Consider I have a controller method get() which calls a few service methods working with database.

使整个控制器方法成为事务性的还是只是每个服务方法都正确?

Is it correct to make the entire controller method transactional or just every service method?

在我看来,我们必须使 get() 成为事务性的,因为它执行相关操作.

It seems to me that we must make get() transactional because it performs associated operations.

推荐答案

我更喜欢仅将需要事务性的服务方法设为事务性,并在服务中而不是在控制器中控制事务性.您可以创建一个服务方法,该方法可以包含其他服务方法,并使用 spring 事务在@Transactional 注释中通过传播来管理事务.

I prefer to make only transactional the service methods that need to be transactional and control the transactionality in the service not in the controller. You can create a service method which englobes other service methods and with the spring transaction manage the transaction with propagation in @Transactional annotation.

@Transactional(propagation =...)

编辑

如果我有 2 个方法,例如 saveUser() 和 saveEmail()(因为我将电子邮件存储在数据库中以便稍后发送 - 就像队列一样),我将在我的服务中创建一个方法 saveUserAndSendEmail(User user)交易.此方法将在 @Repository 组件中分别调用 saveUser 和 saveEmail() ,因为它们处理数据库.因此,我会将它们放在@Repository 组件中以处理数据库的方法,然后我在@Service 组件中控制事务性.然后控制器只需担心提供数据并在需要时进行调用.但是我做了一个事务,因为我不想在整个方法执行成功之前提交数据库中的更改.

If I had 2 methods for example saveUser() and saveEmail() (because I store the emails in a database to send them later - like a queue) I would create in my service a method saveUserAndSendEmail(User user) which would be transactional. This method would call saveUser and saveEmail() each one in a @Repository component because they deal with the database. So I would put them in the @Repository components the methods to handle with the database and then I control the transactionality in the @Service component. Then the controller will only have to worry about providing the data and calling whenever they are needed. But I make a transaction because I don't want to commit changes in thedatabase until the whole method is executed successfully.

但这是我通常使用的风格,我并不是说这一定是要走的路.

But this is the style I usually use, I'm not saying that this must be the way to go.

这篇关于事务性:控制器与服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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