首页 > 解决方案 > EntityManager 合并()挂起

问题描述

当我尝试通过多个调用合并多个实体时,我的服务似乎在尝试背靠背合并时第二次挂起,但是如果我只用任何一个实体调用这个实体,例如service.updateFoo(foo1);service.updateFoo(foo2);

这是我尝试过的

服务:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;

@Service
public class FooService {

  private final EntityManagerFactory entityManagerFactory;
  private final FooRepository fooRepository;

  @Autowired
  public FooService(
      EntityManagerFactory entityManagerFactory, FooRepository fooRepository) {
    this.entityManagerFactory = entityManagerFactory;
    this.fooRepository = fooRepository;
  }
  
  public Foo updateFoo(Foo foo) {
    EntityManager entityManager = entityManagerFactory.createEntityManager();
    EntityTransaction entityTransaction = entityManager.getTransaction();
    entityTransaction.begin();
    try {
      foo = entityManager.merge(foo); // hangs here the 2nd time
    } finally {
      entityManager.flush();
      entityTransaction.commit();
      entityManager.clear();
    }

    return foo;
  } 
}

回购

@Repository
public interface FooRepository extends CrudRepository<Foo, Long> {
}

实体

@Setter
@Getter
@Entity
@Table(name = "foo")
public class Foo implements Serializable {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private long id;

  @NonNull private String userId;
  @Embedded private FooCaller fooCaller;

  @NonNull
  @Enumerated(EnumType.STRING)
  private FooStatus status;
}

我做错了什么?

标签: javaspringjpa

解决方案


推荐阅读