Background: When I tried to create a Student object, I met an error coming from the hibernate.
Here's the error message:
"org.springframework.dao.InvalidDataAccessApiUsageException: org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing : com.dailycodeworksbqrcodedemo.model.Student.parent -> com.dailycodeworksbqrcodedemo.model.Parent; nested exception is java.lang.IllegalStateException: org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing : com.dailycodeworksbqrcodedemo.model.Student.parent
JSON example:
Student class before fixing error
Parent Class before fixing error
Solution: fix the student class by adding (cascade = CascadeType.PERSIST)
The @ManyToOne
annotation with CascadeType.PERSIST
specifies that the parent object should be persisted when the associated student object is persisted. This means that when you save a student, it will also save the associated parent if it is not already persisted. With this configuration, when you save a student using the repository, it will automatically persist the associated parent if it's a new parent object. However, if the parent object is already persisted, it will not update the parent's state.
Know more about JPA/Hibernate Cascade Types:Overview of JPA/Hibernate Cascade Types. | Baeldung