1

We are facing problems with how hibernate handles multiple inserts.

First, We have several instances of a class where the primary key is not auto-generated. We save them in a loop then call flush. But hibernate creates separate insert queries as shown in hibernate log (show_sql). Is this normal? Can we make it use a single insert rather than multiple ones?

Second, Look at the following code:

public void saveCourse() {
    Course course = new Course();
    List<Student> studentList = new ArraryList();
    studentList.add(getStudentService().save(new Student(“hasan”,”askari”)));
    studentList.add(getStudentService().save(new Student(“ali”,”alavi”)));
    studentList.add(getStudentService().save(Student(“reza”,”rezaei”)));
    course.setStudents(studentList);
    getCourseService().save(course);    
}

When the course object is being saved hibernate create separate inserts for table course_student. Why?

Here are our classes:

@Entity
@Table(name = "student ")
public class Student {
    private Long id;
    private String name;
    private String family;
    ….
}    

@Entity
@Table(name = "course ")
public class Course {
    private Long id;
    private List<Student> students;

    @OneToMany
    @JoinTable(name = "course_student")
   public List<Student> getStudents() {
        return students;
    }
    public void setStudents(List<Student> students) {
        this.students = students;
    }
}

Jdbc batch size is made: hibernate.jdbc.batch_size=100 and we flush the session after every 100 saves.

2
  • If I understood right, that is the correct behavior. Hibernate is going to insert records on the JoinTable when you persist Course. Otherwise, Courses would be persisted without any Student. Commented Sep 7, 2013 at 19:56
  • The problem is that why 10 inserts is done for a course with 10 students? why hibernate does not handle it with one insert? Commented Sep 9, 2013 at 12:34

1 Answer 1

2

You must add this option to hibernate connection URL: rewriteBatchedStatements=true

<property name="hibernate.connection.url">jdbc:mysql://localhost/hibernateTest?rewriteBatchedStatements=true</property>

Note that this does not change anything in hibernate log (generated by setting show_sql=true). It shown separate inserts even after adding this option to jdbc url. To ensure it really works you should check mysql log.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.