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 s开发者_C百科o 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...
}
}
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
精彩评论