I know this is a very common topic, I have also read a lot of blogs and post related to it but most of them just tell the difference that save()
returns an identifier and persist()
has return type of void. Both belong to the package org.hibernate
.
I have read the following posts too-
-
For those people who do not use intelli j,
instructor_id
serves as a foreign key in the tablecourse
which referencesinstructor(id)
and similarly for the other table as well.I was trying to save courses to an instructor in the following way-
session.beginTransaction(); // get the instructor from db int theId = 1; Instructor tempInstructor = session.get(Instructor.class, theId); // create some courses Course tempCourse1 = new Course("Java"); Course tempCourse2 = new Course("Maven"); tempInstructor.add(tempCourse1, tempCourse2); session.save(tempInstructor); // Commit transaction session.getTransaction().commit();
The related entry in
Instructor
class-@OneToMany(mappedBy = "instructor", cascade = {CascadeType.DETACH, CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH}) private List<Course> courses;
The
add
method inInstructor
-public void add(Course... tempCourse) { if (courses == null) { courses = new ArrayList<>(); } for (Course course : tempCourse) { courses.add(course); course.setInstructor(this); } }
The related entry in
Course
class-@ManyToOne(cascade = {CascadeType.DETACH, CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH}) @JoinColumn(name = "instructor_id") private Instructor instructor; // Associated Entity
When I try to save the instructor with
session.save(tempInstructor);
none of the courses are saved with the instructor when I usesession.save()
but when I usesession.persist()
both the courses are also saved. I know thatsave()
returns an identifier andINSERTS
object immediately then why is it not saving the courses? Kindly help me solve this confusion. I also read somewheresave() is not good in a long-running conversation with an extended Session/persistence context.
Can anybody please explain what all happens when I call save and why aren't the objects saved. Sorry if I am missing something basic, I am new to this.
CodePudding user response:
In your example
tempCourse1
andtempCourse2
are in a detached state, so to make a relation you need to persist them.Both
save
andpersist
doing the same thing, butsave
is Hibernate's API andpersist
is a part of JPA specification.On your entity, you have
CascadeType.PERSIST
which relates only to thepersist
method. To makesave
behave the same you should addorg.hibernate.annotations.CascadeType#SAVE_UPDATE
to yourManyToOne
annotation.