0

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:

I have a database as follows.

Database

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
VIAGC
  • 639
  • 6
  • 14

1 Answers1

1

In your example, tempCourse1 and tempCourse2 are in a detached state, so to make a relation you need to persist them.

Both save and persist doing the same thing, but save is Hibernate's API and persist is a part of the JPA specification.

On your entity, you have CascadeType.PERSIST which relates only to the persist method. To make save behave the same, you should add org.hibernate.annotations.CascadeType#SAVE_UPDATE to your ManyToOne annotation.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
geobreze
  • 2,274
  • 1
  • 10
  • 15