【问题标题】:When does a object become detached in Spring Data JPA?Spring Data JPA 中的对象何时分离?
【发布时间】: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


    【解决方案1】:

    在 Spring Boot 中,参数 spring.jpa.open-in-viewset to true by default

    我想你应该把它转给false

    来自 java 文档:

    注册 OpenEntityManagerInViewInterceptor。将 JPA EntityManager 绑定到线程以完成请求的整个处理。

    【讨论】:

    • 甚至不知道该选项存在。谢谢!
    猜你喜欢
    • 2015-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-15
    • 2021-05-27
    • 1970-01-01
    相关资源
    最近更新 更多