Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA+Hibernate(J2SE) @OneToMany - Millions of records slows adding a new object down

I'm using JPA+Hibernate with a PostGre SQL database in a J2SE project.
I have 2 entities A and B. A has a @OneToMany relationship to B.
In my domain model A might reference millions of B's. When I add a new object to the collection it takes minutes to complete.

@OneToMany(cascade=CascadeType.PERSIST)
Collection<B> foo = new ArrayList<B>(); // might contain millions of records
//...
// this takes a lot of time
foo.add(new B());

I think that JPA fetches the whole collection before inserting the new object. Is there a possibility to configure the relationship so that by adding a new object to the collection no fetch operation is performed?

like image 918
Marc-Christian Schulze Avatar asked Aug 30 '10 13:08

Marc-Christian Schulze


1 Answers

@OneToMany relationships are lazy loaded when using JPA. That means that any call to foo will result in JPA loading all entries referenced in the database.

The only way I know to avoid this is to reverse your relationship, and defining a @ManyToOne relationship on B (pointing to A). This way, you don't have a collection that need to be loaded to insert a new object in your database.

Here is a code sample:

public class B {

    @ManyToOne
    private A a;

    public void foo() {
        A a = new A();
        B b = new B();
        b.setA(a); // Instead of a.getFoo().add(b);
        // Persist b in database...
    }

}
like image 119
Vivien Barousse Avatar answered Oct 19 '22 00:10

Vivien Barousse