JPA将主键和外键保存在一起

Spa*_*ner 3 java hibernate jpa

我有两个实体DealEntity,DealTypeEntity 并且他们是相关的 -

@Entity
class DealEntity{
  @ManyToOne(fetch = FetchType.EAGER)
  @JoinColumn(name = "DEAL_TYPE_ID")
  private DealTypeEntity dealTypeEntity;
}
Run Code Online (Sandbox Code Playgroud)

我试图通过创建包含DealTypeEntity ref的DealEntity实例来保存.

我正在使用JPA,它给了我例外 entityManager.persist(entity)

     Oct 17, 2013 3:36:34 PM org.apache.catalina.core.StandardWrapperValve invoke
     SEVERE: Servlet.service() for servlet [dispatcherServlet] in context with path             [/Travel-Portal] threw exception [Request processing failed; nested exception is          org.springframework.dao.InvalidDataAccessApiUsageException:org.hibernate.TransientPropertyV alueException: object references an unsaved transient instance - save the transient  instance before flushing: training.impetus.tp.model.DealEntity.dealTypeEntity ->  training.impetus.tp.model.DealTypeEntity; nested exception is  java.lang.IllegalStateException: org.hibernate.TransientPropertyValueException: object  references an unsaved transient instance - save the transient instance before flushing:  training.impetus.tp.model.DealEntity.dealTypeEntity ->  training.impetus.tp.model.DealTypeEntity] with root cause
 org.hibernate.TransientPropertyValueException: object references an unsaved transient i nstance - save the transient instance before flushing:  training.impetus.tp.model.DealEntity.dealTypeEntity ->  training.impetus.tp.model.DealTypeEntity
    at org.hibernate.engine.spi.CascadingAction$8.noCascade(CascadingAction.java:380)
    at org.hibernate.engine.internal.Cascade.cascade(Cascade.java:176)
    at o rg.hibernate.event.internal.AbstractFlushingEventListener.cascadeOnFlush(AbstractFlushingEv entListener.java:160)
    at o  rg.hibernate.event.internal.AbstractFlushingEventListener.prepareEntityFlushes(AbstractFlus hingEventListener.java:151)
    at o    rg.hiborg.hibernate.event.internal.AbstractFlushingEventListener.prepareEntityFlushes(AbstractFlushingEventListener.java:151)
    at org.hib
Run Code Online (Sandbox Code Playgroud)

Sub*_*mal 14

您可以执行错误消息建议的"在刷新之前保存瞬态实例"

entityManager.persist(dealTypeEntity);
entityManager.persist(dealEntity);
Run Code Online (Sandbox Code Playgroud)

或者您可以将DealEntity中的注释更改为

@ManyToOne(fetch = FetchType.EAGER, cascade=CascadeType.PERSIST)
// then persisting DealEntity would persist the childs also
entityManager.persist(dealEntity);
Run Code Online (Sandbox Code Playgroud)