如何使用 spring-boot 和 JPA 持久化包含另一个未持久化实体的多个相同实例的新实体?

How to persist a new entity containing multiple identical instances of another unpersisted entity with spring-boot and JPA?

概览:

我正在构建一个 spring-boot 应用程序,它部分地从外部 REST 服务中检索一些实体,并将其与本地数据库中保存的实体的先前版本进行比较。

我正在用 @PersistenceContext 注入 EntityManager,并使用它来处理数据库,因为有许多实体类型,并且模块最初不知道该类型。我可以从工厂获得 JpaRepository,但不同实体类型的数量可能会增加,如果可能的话我宁愿不依赖它。

问题:

当模块检索到它不在数据库中的实体时,它会执行一些业务逻辑,然后尝试保留新实体。

作为相关实体之一的 Person class 包含三个 Site 类型的字段,它们通常包含相同的对象。

当我尝试在多个字段中使用 CascadeType.PERSIST 持久化一个具有相同 Site 对象的新 Person 时,我得到一个 EntityExistsException(请参阅堆栈跟踪(1 )).

当我从 Site 字段中删除 CascadeType.PERSIST,并尝试在多个字段中保留一个具有相同 Site 对象的新 Person 时,我得到a TransientPropertyValueException(参见堆栈跟踪 (2))。

我想我理解了两个异常发生的原因:

我尝试删除 @Transactional 注释并开始并自己提交一个 EntityTransaction,但我得到一个 IllegalStateException(请参阅堆栈跟踪 (3)),尽管我认为这是预期的 spring 应该自己处理交易。

我查看了类似问题的答案(例如 this, this),但都建议改变 CascadeType 的一些变体。

在另一个问题中,有人建议确保所讨论的实体被 equals() 方法正确评估,所以我检查了调试器,((Person)newEntity).currentSite.equals(((Person)newEntity).homeSite) 评估为真。

我如何才能在多个字段中始终如一地 persisting/merging 具有相同对象的实体?


编辑: 我还尝试了层叠类型与 fetch = FetchType.EAGER 的各种组合,但这不会在它们各自的异常中产生任何变化。


编辑 2: 我试过使用 JpaRepository 而不是 EntityManager,并根据什么有效地获得相同的异常集我正在使用的级联类型。

如果我使用 PERSIST,但不使用 MERGE,我会得到一个 EntityNotFoundException(参见堆栈跟踪 (4)),如果我同时使用 PERSISTMERGE 我收到一个 InvalidDataAccessApiUsageException`(请参阅堆栈跟踪 (5))。


人:

@EqualsAndHashCode(callSuper = true)
@javax.persistence.Entity
@XmlDiscriminatorValue("person")
@XmlRootElement(name = "person")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlSeeAlso({Subscriber.class})
public class Person extends MobileResource implements Serializable {

    private static final Logger LOG = LogManager.getLogger(Person.class);

    private String firstName;
    private String surname;

    public Person() {
        super();
    }

    public Person(Long id) {
        super(id);
    }

    public Person(Person that) {
        super(that);
        this.firstName = that.firstName;
        this.surname = that.surname;
    }

    // getters && setters
}

移动资源:

@EqualsAndHashCode(callSuper = true)
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
@XmlRootElement(name = "resource")
@XmlDiscriminatorNode("@type")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlSeeAlso({Vehicle.class, Person.class})
public abstract class MobileResource extends Resource implements Serializable {

    private static final Logger LOG = LogManager.getLogger(MobileResource.class);

    @ManyToOne(cascade = CascadeType.ALL)
    private MobileResourceStatus status;
    private Long                 incidentId;
    @ManyToOne(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.REMOVE, CascadeType.DETACH})
    private Site                 homeSite;
    @ManyToOne(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.REMOVE, CascadeType.DETACH})
    private Site                 currentSite;
    @ManyToOne(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.REMOVE, CascadeType.DETACH})
    private Site                 relocationSite;

    public MobileResource() {
        super();
    }

    public MobileResource(Long id) {
        super(id);
    }

    public MobileResource(MobileResource that) {
        super(that);
        this.status = that.status;
        this.incidentId = that.incidentId;
        this.homeSite = that.homeSite;
        this.currentSite = that.currentSite;
        this.relocationSite = that.relocationSite;
    }

    // getters && setters
}

站点:

@EqualsAndHashCode(callSuper = true)
@javax.persistence.Entity
public class Site extends Resource implements Serializable {

    private static final Logger LOG = LogManager.getLogger(Site.class);

    private String location;

    public Site() {
        super();
    }

    public Site(Long id) {
        super(id);
    }

    public Site(Site that) {
        super(that);
        this.location = that.location;
    }
}

资源:

@EqualsAndHashCode
@MappedSuperclass
@XmlRootElement
@XmlSeeAlso({MobileResource.class})
public abstract class Resource implements Entity, Serializable {

    private static final Logger LOG = LogManager.getLogger(Resource.class);

    @Id
    private Long            id;
    private String          callSign;
    @XmlPath(".")
    private LatLon          latLon;
    private Long            brigadeId;
    private Long            batchId;
    @ManyToMany(cascade = CascadeType.ALL)
    private List<Attribute> attributes;
    @ManyToOne(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.REMOVE, CascadeType.DETACH})
    private ResourceType    type;

    public Resource() {
    }

    public Resource(Long id) {
        this.id = id;
    }

    public Resource(Resource that) {
        this.id = that.id;
        this.callSign = that.callSign;
        this.latLon = that.latLon;
        this.attributes = that.attributes;
        this.batchId = that.batchId;
        this.brigadeId = that.brigadeId;
        this.type = that.type;
    }

    // getters && setters
}

DefaultEntityMessageHandler:

@Component
public class DefaultEntityMessageHandler implements EntityMessageHandler {


    @PersistenceContext
    private EntityManager entityManager;

    @Override
    @Transactional
    public void handleEntityMessage(EntityMessageData data, Message message) {

        // business logic
        if (newEntity != null) {
            if (oldEntity != null)
                entityManager.merge(newEntity);
            else
                entityManager.persist(newEntity);
        }
    }
}

堆栈跟踪 (1):

2018-06-06 12:05:15,975 ERROR ActiveMQMessageConsumer - ID:cpt-9225-1528283097161-1:1:1:1 Exception while processing message: ID:cpt-8919-1528281875592-1:1:1:1:4 
javax.persistence.EntityExistsException: A different object with the same identifier value was already associated with the session : [my.class.path.entity.resource.site.Site#738]
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:118)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:157)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:164)
at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:813)
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:773)
at org.hibernate.jpa.event.internal.core.JpaPersistEventListener.cascade(JpaPersistEventListener.java:80)
at org.hibernate.engine.internal.Cascade.cascadeToOne(Cascade.java:467)
at org.hibernate.engine.internal.Cascade.cascadeAssociation(Cascade.java:392)
at org.hibernate.engine.internal.Cascade.cascadeProperty(Cascade.java:193)
at org.hibernate.engine.internal.Cascade.cascade(Cascade.java:126)
at org.hibernate.event.internal.AbstractSaveEventListener.cascadeBeforeSave(AbstractSaveEventListener.java:414)
at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:252)
at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:182)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:125)
at org.hibernate.jpa.event.internal.core.JpaPersistEventListener.saveWithGeneratedId(JpaPersistEventListener.java:67)
at org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:189)
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:132)
...

正在更改 MobileResource 中的级联类型:

@ManyToOne(fetch = FetchType.LAZY, cascade = {CascadeType.REMOVE, CascadeType.DETACH})
private Site                 homeSite;
@ManyToOne(fetch = FetchType.LAZY, cascade = {CascadeType.REMOVE, CascadeType.DETACH})
private Site                 currentSite;
@ManyToOne(fetch = FetchType.LAZY, cascade = {CascadeType.REMOVE, CascadeType.DETACH})

堆栈跟踪 (2):

2018-06-06 12:19:24,084 ERROR ExceptionMapperStandardImpl - HHH000346: Error during managed flush [org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing : my.class.path.entity.resource.mobile_resource.person.Person.currentSite -> my.class.path.entity.resource.site.Site]
2018-06-06 12:19:24,093 ERROR ActiveMQMessageConsumer - ID:cpt-9436-1528283955454-1:1:1:1 Exception while processing message: ID:cpt-8919-1528281875592-1:1:1:1:8
org.springframework.dao.InvalidDataAccessApiUsageException: org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing : my.class.path.entity.resource.mobile_resource.person.Person.currentSite -> my.class.path.entity.resource.site.Site; nested exception is java.lang.IllegalStateException: org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing : my.class.path.entity.resource.mobile_resource.person.Person.currentSite -> my.class.path.entity.resource.site.Site
    at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:365)
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:227)
    at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:540)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:746)
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:714)
...

堆栈跟踪 (3):

2018-06-06 13:29:35,594 ERROR ActiveMQMessageConsumer - ID:cpt-9864-1528288166188-1:1:1:1 Exception while processing message: ID:cpt-8919-1528281875592-1:1:1:1:9
java.lang.IllegalStateException: Not allowed to create transaction on shared EntityManager - use Spring transactions or EJB CMT instead
    at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:254)
    at com.sun.proxy.$Proxy114.getTransaction(Unknown Source)
    at my.class.path.entity_controller.DefaultEntityMessageHandler.handleEntityMessage(DefaultEntityMessageHandler.java:60)
    at my.class.path.entity_listener.listeners.IdExtractorMessageListener.onMessage(IdExtractorMessageListener.java:41)
...

堆栈跟踪 (4)

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2018-06-06 15:26:36,143 ERROR SpringApplication - Application run failed
java.lang.IllegalStateException: Failed to execute CommandLineRunner
    at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:793)
    at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:774)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:335)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1246)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1234)
    at my.class.path.OfficerSubscription.main(OfficerSubscription.java:44)
Caused by: org.springframework.orm.jpa.JpaObjectRetrievalFailureException: Unable to find my.class.path.entity.resource.site.Site with id 738; nested exception is javax.persistence.EntityNotFoundException: Unable to find my.class.path.entity.resource.site.Site with id 738
    at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:373)
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:227)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:507)
    at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:61)
    at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:242)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:153)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
...

堆栈跟踪 (5)

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2018-06-06 15:31:54,840 ERROR SpringApplication - Application run failed
java.lang.IllegalStateException: Failed to execute CommandLineRunner
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:793)
at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:774)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:335)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1246)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1234)
at my.class.path.OfficerSubscription.main(OfficerSubscription.java:44)
Caused by: org.springframework.dao.InvalidDataAccessApiUsageException: Multiple representations of the same entity [my.class.path.entity.resource.site.Site#738] are being merged. Detached: [FJE84 - Uckfield]; Detached: [FJE84 - Uckfield]; nested exception is java.lang.IllegalStateException: Multiple representations of the same entity [my.class.path.entity.resource.site.Site#738] are being merged. Detached: [FJE84 - Uckfield]; Detached: [FJE84 - Uckfield]
at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:365)
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:227)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:507)
at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:61)
at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:242)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:153)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:135)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:61)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212)
at com.sun.proxy.$Proxy122.save(Unknown Source)
at my.class.path.OfficerSubscription.run(OfficerSubscription.java:81)
at my.class.path.OfficerSubscription$$FastClassBySpringCGLIB$5870eb.invoke(<generated>)
    ...

经过几天的搜索,我终于在我的 spring 引导项目中解决了这个问题。

application.yaml 文件中添加以下块:

    spring:
      jpa:
        properties:
          hibernate:
            enable_lazy_load_no_trans: true
            event:
              merge:
                entity_copy_observer: allow