I have two tables like this
at first, i try to set course_id foreign key in review table to have not null constraint for the sake of data integrity.
So i create annotated class like for these two table like below:
@Data
@Entity
@Table(name = "course")
public class Course {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "course_id")
private int id;
@Column(name = "name")
private String name;
@OneToMany(fetch = FetchType.LAZY,cascade = CascadeType.ALL)
@JoinColumn(name = "course_id")
private List<Review> reviews;
public Course(){}
public Course(String name){
this.name = name;
}
public void addReview(Review review){
if(this.reviews == null){
this.reviews = new ArrayList<>();
}
this.reviews.add(review);
}
}
@Data
@Entity
@Table(name = "review")
public class Review {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "review_id")
private int reviewId;
@Column(name = "rating")
private int rating;
public Review(){}
public Review(int rating){
this.rating = rating;
}
}
and i create simple app to add review to an exsiting course like code below:
session.beginTransaction(); // get instructor from db Course course = session.get(Course.class, 3); // create review Review review1 = new Review(4); course.addReview(review1); // save to db session.save(course); session.getTransaction().commit();
but this program will throw an error because it violates not null constraint i set in database before
Caused by: org.postgresql.util.PSQLException: ERROR: null value in column “course_id” violates not-null constraint
but if remove the not null constraint this program works fine because hibernate will execute insert with null value first than update the value like below:
Hibernate: insert into review (rating) values (?) Hibernate: update review set course_id=? where review_id=?
is there a way for hibernate to insert directly with course_id value so i can keep the not null constraint?
Thanks!
Advertisement
Answer
You need to specify in the mapping that the column is not nullable:
@JoinColumn(name = "course_id", nullable = false)
