Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA: How to cascade save entities when child has Embedded Id?

I've the following parent entity.

@Entity
@Table(name = "vital_entry")
public class VitalEntry {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "vital_entry_id", columnDefinition = "INT")
    private int vitalEntryId;

    @OneToMany(mappedBy = "vitalEntry", cascade = CascadeType.ALL)
    private Set<VitalEntryValues> vitalEntryValues = new HashSet<>();

    .... other fields

}

and here's my child entity

@Entity
@Table(name = "vital_entry_values")
public class VitalEntryValues {

    @EmbeddedId
    private VitalEntryValuesId vevId;

    @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.MERGE)
    @MapsId("vital_entry_id")
    @JoinColumn(name = "vital_entry_id", columnDefinition = "INT")
    private VitalEntry vitalEntry;

    @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.MERGE)
    @MapsId("vital_id")
    @JoinColumn(name = "vital_id", columnDefinition = "INT")
    private Vitals vitals;

    @Column(name = "vital_unit_id", insertable = false, updatable = false)
    private int vitalUnitId;

    @Basic
    private double value;

    @Basic
    @Column(columnDefinition = "INT")
    private int type;

    @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.MERGE)
    @JoinColumn(name = "vital_unit_id", columnDefinition = "INT")
    private VitalUnits vitalUnits;


    public VitalEntryValues() {
    }

    public VitalEntryValues(double value, int type, VitalEntry vitalEntry, VitalUnits vitalUnits, Vitals vitals) {
        this.value = value;
        this.type = type;
        this.vitalEntry = vitalEntry;
        this.vitalUnits = vitalUnits;
        this.vitals = vitals;
    }

}

and the EmbeddedId class:

@Embeddable
public class VitalEntryValuesId implements Serializable {

    @Column(name = "vital_entry_id", columnDefinition = "INT", insertable = false, updatable = false)
    private int vitalEntryId;

    @Column(name = "vital_id", columnDefinition = "INT", insertable = false, updatable = false)
    private int vitalId;
}

and I'm saving it like this:

VitalEntry = new VitalEntry(accountId, vitalEntryVO.getDateTime(),
                DateUtility.getCurrentGMTDate(), vitalEntryVO.getNotes(), vitalEntryVO.getVitalEntryType(), vitalEntryVO.getParentVitalId());

Set<VitalEntryValues> vitalEntryValues = new HashSet<>();

for (VitalEntryValueVO value : vitalEntryVO.getValues()) {
    VitalEntryValues values = new VitalEntryValues(value.getValue(), vitalEntryVO.getType(), vitalEntry,
    vitalRepo.findUnit(value.getUnitId()), vitalRepo.findOne(value.getVitalId()));
    vitalEntryValues.add(values);
}
vitalEntry.setVitalEntryValues(vitalEntryValues);
vitalEntry =  vitalEntryRepo.save(vitalEntry);

but on save I'm getting this exception:

Caused by: org.hibernate.id.IdentifierGenerationException: null id generated for:class com.v2.entity.VitalEntryValues
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:107)
    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)
    at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:804)
    at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:771)
    at org.hibernate.jpa.event.internal.core.JpaPersistEventListener$1.cascade(JpaPersistEventListener.java:80)
    at org.hibernate.engine.internal.Cascade.cascadeToOne(Cascade.java:458)
    at org.hibernate.engine.internal.Cascade.cascadeAssociation(Cascade.java:383)
    at org.hibernate.engine.internal.Cascade.cascadeProperty(Cascade.java:193)
    at org.hibernate.engine.internal.Cascade.cascadeCollectionElements(Cascade.java:491)
    at org.hibernate.engine.internal.Cascade.cascadeCollection(Cascade.java:423)
    at org.hibernate.engine.internal.Cascade.cascadeAssociation(Cascade.java:386)
    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.cascadeAfterSave(AbstractSaveEventListener.java:445)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:281)
    at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:182)
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:113)
    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)
    at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:58)
    at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:780)
    at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:765)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:298)
    at com.sun.proxy.$Proxy555.persist(Unknown Source)
    at org.springframework.data.jpa.repository.support.SimpleJpaRepository.save(SimpleJpaRepository.java:508)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:504)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:489)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:461)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:56)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)

What am I doing wrong here? Any help is appreciated..

Edit:

@Entity
@Table(name = "vitals")
public class Vitals {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "vital_id", columnDefinition = "INT")
    private int vitalId;

    @Basic
    @Column(name = "has_value")
    private boolean hasValue;

    @Basic
    @Column(name = "is_decimal")
    private boolean isDecimal;

    @Basic
    @Column(name = "is_oneday_reading")
    private boolean isOnedayReading;

    @Basic
    @Column(length = 100)
    private String name;

    @Basic
    @Column(name = "parent_id", columnDefinition = "INT")
    private int parentId;

    @OneToMany(targetEntity = PatientVitals.class, mappedBy = "vitals", cascade = CascadeType.MERGE)
    private Set<PatientVitals> patientVitals = new HashSet<PatientVitals>();

    @Basic
    @Column(columnDefinition = "INT")
    private int type;

    @OneToMany(targetEntity = VitalEntryValues.class, mappedBy = "vitals", cascade = CascadeType.MERGE)
    private Set<VitalEntryValues> vitalEntryValues = new HashSet<VitalEntryValues>();

    @OneToMany(targetEntity = VitalUnits.class, mappedBy = "vitals", cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REMOVE})
    private Set<VitalUnits> vitalUnits = new HashSet<VitalUnits>();
}
like image 905
Drunken Daddy Avatar asked Jul 31 '17 09:07

Drunken Daddy


1 Answers

Introduction and context

I have used a reduced version of the provided source code that is enough to reproduce the described problem.

So, the analysis and the solution may be incomplete.

Hibernate version:

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>5.2.10.Final</version>
</dependency>

Analysis and solution

1. MapsId annotation usage

Please consider checking the documentation on the MapsId annotation and its usage.

For the provided context it should be:

...
public class VitalEntryValues {
    ...

    @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.MERGE)
    @MapsId("vitalEntryId")
    @JoinColumn(name = "vital_entry_id", columnDefinition = "INT")
    private VitalEntry vitalEntry;

    @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.MERGE)
    @MapsId("vitalId")
    @JoinColumn(name = "vital_id", columnDefinition = "INT")
    private Vitals vitals;

    ...
}

2. Hibernate: EmbeddedId field initialisation

As my experiments shown, the field annotated with the EmbeddedId annotation is also required to be initialised to avoid internal Hibernate exception — org.hibernate.PropertyAccessException. Please refer to the question for the details.

...
public class VitalEntryValues {
    ...

    @EmbeddedId
    private VitalEntryValuesId vevId = new VitalEntryValuesId();

    ...
}

Hope this helps.

like image 159
Sergey Vyacheslavovich Brunov Avatar answered Sep 29 '22 11:09

Sergey Vyacheslavovich Brunov