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?
@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...
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With