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:
- Difference between save() and persist() in Hibernate
- What's the difference between session.persist() and session.save() in Hibernate?
- What are the differences between the different saving methods in Hibernate?
I have a database as follows.
For those people who do not use IntelliJ IDEA, instructor_id
serves as a foreign key in the table course
which references instructor(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 the database
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 in Instructor
-
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 use session.save()
, but when I use session.persist()
both the courses are also saved. I know that save()
returns an identifier and INSERTS
object immediately then why is it not saving the courses?
I also read somewhere
save() is not good in a long-running conversation with an extended Session/persistence context.
What all happens when I call save and why aren't the objects saved?