Reputation: 444
I am using JPA to insert a lot of objects into the database (75.000), knowing that the code below can be called multiple times...
Since I do not want a memory leak, I am asking JPA to flush the EntityManager
after 5.000 persist()
. Indeed, flushing is not commiting anything...
@Stateless
public class TwitterScheduler {
@EJB
private EntityUserFacade facade;
// ids are 5.000
public void do(ids) {
for (long id : ids.getIDs()) {
Entity e = new Entity();
e.set(...);
this.facade.create(e);
}
this.facade.getEntityManager().flush();
}
}
@TransactionManagement(TransactionManagementType.BEAN)
, persist()
will automaticly commit()
the transaction if I am right.But I am worried about performance / memory leak, should I ?
Should I use @Resource UserTransaction utx;
to join somehow the transaction to JPA ? If so how ? Because I cannot is the Transaction Management is set to Container
.
Also I wonder, if I DO NOT FLUSH the EntityManager, I got a memory leak. If I flush the EntityManager using this.facade.getEntityManager().flush();
, it became very slow the more I called do()
method, why ?
Upvotes: 0
Views: 3064
Reputation: 5207
How to commit?
Use transaction attribute on the class or on the method level. Depending on your context, you may need
@TransactionAttribute(TransactionAttributeType.REQUIRED)
or
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
Performance - JPA
JDBC has a possibility to do some operations in a batch mode. You can use it on entity level (as JPA annotation) as well as on JPA implementation specific level (like Hibernate properties file).
Performance - non-JPA
Why are you using JPA? Compare performance of JPA and plain JDBC in your use case. If performance is crucial for you and JDBC is essentially faster, why stick to JPA? JPA is good when you want to work with data in an object oriented way - you want to use a higher abstraction, you want to retrieve and persist objects without caring about low level details, you want to load related objects in a natural way without thinking of joins and indexes. But it may be not the best choice for bulk processing of data. Bulk processing might be more efficient when done in plain JDBC. Think, compare, decide.
Upvotes: 1