Search code examples
hibernatespring-data-jpahibernate-onetomany

Improve hibernate performance with spring Jpa


I have a problem with hibernate which seems very slow when I try to persist my object in database.

So, the concerned model is like this :

@Entity
@Table(name = "T_PARENT")
public class ParentEntity implements Serializable {

    // Id

    // Attributes

    // Child relation
    @OneToMany(cascade = CascadeType.ALL)
    @JoinColumn(name="xxxx")
    private List<ChildEntity> childs;

    // Getters & setters
}

@Entity
@Table(name = "T_CHILD")
public class ChildEntity implements Serializable {

    // Id

    // Attributes

    // Child relation
    @OneToMany(cascade = CascadeType.ALL)
    @JoinColumn(name="yyyyy")
    private List<ChildChildEntity> childs;

    // Getters & setters
}

@Entity
@Table(name = "T_CHILD_CHILD")
public class ChildChildEntity implements Serializable {

    // Id

    // Attributes

    // Getters & setters
}

I use JpaRepository (spring) to manage data in database. We call "save" method on "parent" to persist the "child" and "childChild" (Only parent's repository was created)

With few data, there is no problem (ex : 1 parent / 20 child and for every child there 200 childChild) But when we have an important volume, the hibernate queries are interminables... (ex : 1 parent / 40 child and for every child there are 600 childChild)

Have you any idea how to improve performance with keeping the use of only one repository (parent) because I don't want to split the treatment...

Thanks


Solution

  • You could try to use batch inserts. That way Hibernate will send batches of insert statements to the database and not every single insert.

    Set hibernate.jdbc.batch_size to a value up to 30. But be careful and test if it boosts your performance.

    Read more about that: https://vladmihalcea.com/how-to-batch-insert-and-update-statements-with-hibernate/