[英]Spring Data JPARepository and @Transactional For Multiple Operations inside One Method
The saveUser method doesn't save the user object name change when I have multiple operations inside one method. 当我在一个方法中进行多项操作时,saveUser方法不会保存用户对象名称更改。 If I use @Transactional(propagation = Propagation.REQUIRED) on top of the saveUser service method, it works fine.
如果我在saveUser服务方法的顶部使用@Transactional(propagation = Propagation.REQUIRED),它可以正常工作。 When another class creates a new User object and sets all its values and calls the createUser method, it works fine.
当另一个类创建一个新的User对象并设置其所有值并调用createUser方法时,它将正常工作。 Why do I need @Transactional for the saveUser method?
为什么需要@Transactional作为saveUser方法? In what cases do I need to include @Transactional?
在什么情况下我需要包含@Transactional? I'm using Spring Data and JPA (Hibernate impl).
我正在使用Spring Data和JPA(Hibernate impl)。 Any ideas?
有任何想法吗?
JPA Entity: JPA实体:
@Entity
public class User{
@Id
@GeneratedValue
private Long id;
@Column
private String name;
//getters/setters..etc
}
Spring Service: 春季服务:
@Service
public class UserServiceImpl{
@Autowired
UserRepository userRepository;
public void saveUser(Long id){
User user = userRepository.findById(id);
user.setName("newname");
userRepository.save(user);
}
public void createUser(User user){
userRepository.save(user);
}
}
Spring Data JPA/Hibernate Impl Repository: Spring Data JPA /休眠Impl存储库:
public interface UserRepository extends JpaRepository<User, Long> {
}
The methods in JpaRepository
are transactional by default (readonly for retrieving). 默认情况下,
JpaRepository
中的方法是事务性的(检索时只读)。
Now in your saveUser()
method, you need @Transactional
because you are retrieving an User
by id
and updating it and then again persisting to the database. 现在,在
saveUser()
方法中,您需要@Transactional
因为您要通过id
检索User
并对其进行更新,然后再次将其持久化到数据库中。 Basically, @Transactional(readOnly=true)
is used while reading else @Transactional
is used in Spring Data JPA. 基本上,在Spring Data JPA中使用
@Transactional(readOnly=true)
,而在其他情况下则使用@Transactional
。
User user = userRepository.findById(id);
returns null
to user
if no user is found and user.setName("newname");
返回
null
到user
如果没有用户发现和user.setName("newname");
will give NullPointerException
. 将给出
NullPointerException
。
You need transactions if you update the database state (insert/update/delete) otherwise you'll end up having this behaviour. 如果您更新数据库状态(插入/更新/删除),则需要进行事务处理,否则最终将出现这种行为。
Even if you do read-only operations in your methods, you should annotate them with @Transactional(readOnly=true)
so Spring can optimize the transactional resource. 即使您在方法中执行只读操作,也应使用
@Transactional(readOnly=true)
对其进行注释,以便Spring可以优化事务性资源。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.