SpringBoot JPA不需要@Transactional上的.save()吗? [英] SpringBoot JPA need no .save() on @Transactional?
问题描述
我有一个简短的问题:
我需要在@Transactional
方法上进行repo.save(x)
调用吗?
Do I need a repo.save(x)
call on @Transactional
methods?
我问是因为我没有保存就看到了数据库上的更改,并且没有阅读任何有关它的清晰文档.
I ask cause I see changes on my DB without save, and read no clear docs about it.
那么它是按预期工作的,还是只是(受欢迎的)意外行为?
So is it working as intended, or just a (welcome) unexpected behavior?
示例:
@Autowired
private UserRepo repo;
@Transactional
@PutMapping
public Long put(@RequestBody User user)
{
User u = repo.findOne(user.getId());
u.setName("Paul");
repo.save(u); // DO I NEED THIS LINE?
}
我只是不确定,所以也许有人可以对这个问题有所了解?
I'am just unsure about it, so maybe someone can shed some light on the subject?
推荐答案
如果您检索一个实体,例如在事务方法中使用findOne
方法调用,则此实体已成为受管理的由持久性提供程序提供.
If you retrieve an entity, for example using the findOne
method call within a transactional method it has become managed from that point by the persistence provider.
现在,如果您对该实体(实际上是代理对象)进行任何更改,则在提交事务后,无论调用save
或update
方法的事实如何,这些更改都将保留在数据库中.
Now if you make any changes to that entity (which is actually a proxy object), upon transaction commit, those changes will be persisted to the database, regardless of the fact of invoking the save
or update
methods.
save
或persist
.
请记住,如果您在特定实体上使用detach
或evict
方法,则可以防止在提交时进行任何更改.
Remember that you can prevent making any changes upon commit, if you use detach
or evict
methods on that particular entity before those changes occur.
这篇关于SpringBoot JPA不需要@Transactional上的.save()吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!