6

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?

2 Answers 2

4

@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...
    }

}
1

Use property access instead

@OneToMany(cascade=CascadeType.PERSIST)
public Collection<B> getFoo() {
    return foo;
}

JPA implementations makes use of proxies. But it just works when using property access strategy

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.