SpringBoot JPA 在@Transactional 上不需要 .save() 吗? [英] SpringBoot JPA need no .save() on @Transactional?

查看:42
本文介绍了SpringBoot JPA 在@Transactional 上不需要 .save() 吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简短的问题:

我是否需要对 @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 方法调用,它已成为托管strong> 从那一点由持久性提供者提供.

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.

现在,如果您对该实体(实际上是一个代理对象)进行任何更改,则在事务提交时,这些更改将持久保存到数据库中,而不管调用 saveupdate 方法.

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.

savepersist 当你从头开始创建一个新实体并且持久化提供者还不知道它的存在时必须使用.

save or persist has to be used when you are creating a new entity from scratch and persistence provider does not know of its existance yet.

请记住,如果您在这些更改发生之前对该特定实体使用 detachevict 方法,则可以防止在提交时进行任何更改.

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屋!

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