【发布时间】:2018-07-03 22:56:45
【问题描述】:
我有一个使用 Spring Data Repository 检索对象的服务。该服务未标记为事务性的,因此我假设从存储库返回的任何对象都将被分离,因为事务将被限定为存储库。但是,似乎该对象并未分离,这让我感到惊讶。这是一个代码示例:
public class MyService {
@Autowired
private MyRepository repo;
@Autowired
private EntityManager entityManager;
/**
* Updates a persisted entity based on the given DTO representation.
*/
public MyObjectDto update(MyObjectDto dto) {
MyObjectJpa existing = repo.findOne(dto.getId());
entityManager.isJoinedToTransaction(); // returns false so no transaction should be active in this scope I would assume
entityManager.contains(existing); // this returns true, but I don't know why
if (existing != null) {
MyObjectJpa updated = toJpa(dto);
// calling repo.save(..) modifies the state of 'existing' object which surpised me
MyObjectDto updatedDto = toDto(repo.save(updated));
return updatedDto;
}
return null;
}
为什么我的代码示例中的“现有”对象仍由 entityManager 管理,即使我的服务方法未标记为事务性(即不使用 Spring 中的 @Transactional 注释)?谢谢。
【问题讨论】:
标签: jpa spring-data-jpa spring-data