I have 2 objects, the Discipline and the Category object. These 2 are connected using a MANY-TO-ONE relationship. I am trying to create a new Discipline via Postman using this JSON object:
{
"name": "test_sample"
}
The POJOs:
Discipline:
import org.hibernate.annotations.SQLDelete;
import org.hibernate.annotations.Where;
import javax.persistence.*;
@Entity(name = "discipline")
@Where(clause = "is_deleted=0")
@SQLDelete(sql = "UPDATE discipline SET is_deleted = 1 WHERE id = ?")
public class Discipline extends BaseEntity{
@Column(name = "name")
private String name;
@ManyToOne
@JoinColumn(name = "category_id")
private Category category;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
}
Category:
import org.hibernate.annotations.SQLDelete;
import org.hibernate.annotations.Where;
import javax.persistence.*;
@Entity(name = "category")
@Where(clause = "is_deleted=0")
@SQLDelete(sql = "UPDATE category SET is_deleted = 1 WHERE id = ?")
public class Category extends BaseEntity{
@Column(name = "name")
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
I am receiving this error:
{
"timestamp": "2019-06-06T21:22:42.746+0000",
"status": 500,
"error": "Internal Server Error",
"message": "org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing : com.test.meeting.meeting.data.model.Discipline.category -> com.test.meeting.meeting.data.model.Category; nested exception is java.lang.IllegalStateException: org.hibernate.TransientPropertyValueException: object references an unsaved transient instance - save the transient instance before flushing : com.test.meeting.meeting.data.model.Discipline.category -> com.test.meeting.meeting.data.model.Category",
"path": "/api/v1/discipline"
}
How can I save the Discpline object without setting the relation between these two first.
You should add in your @ManyToOne annotation: cascade=CascadeType.ALL
. The reason why you have this error is that you want to save a child object which is not present in the database and hibernate doesn't allow something like this.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.