V-spring V-spring - 3 months ago 29
Java Question

JPA saving primary and foreign key together

I have two Entities

DealEntity
and
DealTypeEntity

and they are related as-


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


I am trying to save by creating instance of DealEntity which contains DealTypeEntity ref.

I am using JPA and it giving me exception in
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

Answer

Either you do what the error message propose "save the transient instance before flushing"

entityManager.persist(dealTypeEntity);
entityManager.persist(dealEntity);

or you could change the annotation in DealEntity to

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