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_idserves as a foreign key in the tablecoursewhich 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
Instructorclass-@OneToMany(mappedBy = "instructor", cascade = {CascadeType.DETACH, CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH}) private List<Course> courses;The
addmethod 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
Courseclass-@ManyToOne(cascade = {CascadeType.DETACH, CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH}) @JoinColumn(name = "instructor_id") private Instructor instructor; // Associated EntityWhen 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 andINSERTSobject 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
tempCourse1andtempCourse2are in a detached state, so to make a relation you need to persist them.Both
saveandpersistdoing the same thing, butsaveis Hibernate's API andpersistis a part of JPA specification.On your entity, you have
CascadeType.PERSISTwhich relates only to thepersistmethod. To makesavebehave the same you should addorg.hibernate.annotations.CascadeType#SAVE_UPDATEto yourManyToOneannotation.
