英文:
Spring @Transactional best practices
问题
我想知道我对 @Transactional
的实现是否正确。
当我第一次了解到 @Transactional
时,我在我的存储库类中使用它,在每个调用多次 mongodb 的方法之上使用。
但是,我停止使用了那种方法,我将 @Transactional
放在我的服务类之上,以便我的服务的每个方法在单个事务中运行。例如,从数据库中查找对象,验证用户输入,然后修改对象并将其保存在数据库中..要知道,有时我需要抛出异常,比如未找到或错误的请求...
我的实现正确吗?
英文:
i wanna know if my implementation of @Transactional
is correct or not.
when I got to know @Transactional
for the first time, i used it in my repository classes, above each method that makes multiple calls to mongodb at once.
But, i stopped using that approach, and put @Transactional
above my service classes, so that each method of my services runs in a single transaction. for example, find an object from the database, validate the user input, then modify the object and save it in the database .. knowing that sometimes I need to throwe a exception, like not found, or bad request...
is my implementation correct?
答案1
得分: 0
通常情况下,当您希望方法中的所有操作都在一个事务中执行时,服务方法会使用 @Transactional 进行注解。
英文:
Yes, usually service methods are annotated with @Transactional when you want everything in that method to happen in one transaction.
答案2
得分: 0
你的方法不会引起任何问题,我们在希望方法中的语句在一个事务中执行时使用 @Transactional 操作。通常我们在服务类中使用它,但即使在其他地方使用也不会有任何问题。
如果你需要了解它的工作原理,可以查看
https://dzone.com/articles/how-does-spring-transactional
英文:
Your approach will not cause any problem, we use @Transactional operation when we want the statement in the method to happen in one transaction. Generally we use it in service class but even if it is used elsewhere will not give any problem.
If you need a details of how it works can see
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论