1

I'm upgrading Hibernate4 to Hibernate5 (Spring 4.3.7) (Spring-data-jpa 1.11.1) and facing the problem with saving of bidirectionally associated entities save using JpaRepository.save(ownerObject).

Here are my entities :-

DataType (Owner Entity) :-

@Entity
@Table(name = "DATATYPE")
public class DataType {

    private List<DataFormat> mFormats;

    public DataType() {
        mFormats = new ArrayList<DataFormat>();
    }

    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true, mappedBy = "dataType")
    public List<DataFormat> getFormats() {
        return mFormats;
    }

    public void setFormats(List<DataFormat> formats) {
        mFormats = formats;
    }   
}

DataFormat Entity (Inverse side):-

@Entity
@Table(name = "DATAFORMAT")
public class DataFormat {

    private DataType mDataType;

    public DataFormat() {
    }

    @ManyToOne
    @ForeignKey(name = "DATATYPE_FK")
    @JoinColumn(name = "DATATYPE_ID")
    public DataType getDataType() {
        return mDataType;
    }

    public void setDataType(DataType dataType) {
        mDataType = dataType;
    }
}

Save/Persist the entities :-

DataType dataType = dataTypeRepository.findOne("DATE_TIME");
if (dataType == null) {
    dataType = new DataType();
}
final DataFormat customFormat = new DataFormat();
dataType.setDefaultFormat(customFormat);
dataTypeRepository.save(dataType);

This works perfect with Hibernate4, that first saves the DataType and then DataFormat. But with Hibernate5, it tries to save the DataFormat (inverse side) first, and then result into error in my case since my DB has constraints for DataFormat to have owner reference.

Although it works if I save the entities like this at the place of dataTypeRepository.save(dataType); :-

entityManager.persist(dataFormat);
entityManager.persist(dataType);

What could be the problem here.

Abhishek-M
  • 410
  • 2
  • 14
  • Try setting both side of the relation and then persisting it. – Abdullah Khan Jun 12 '17 at 08:20
  • Now i have more information about the problem, With hibernate 5 the "hibernate.order_inserts=true" configuration leads into this problem. If i set it to 'false' then everything works fine. With hibernate 4 it was working, there seems to be something changed in hibernate 5 related to these configuration. – Abhishek-M Jun 15 '17 at 11:15

0 Answers0