I have a method that persists lots of rows on the database, it's something like this:
private EntityManager em;
@PostConstruct
public void init() {
Map props = new HashMap();
props.put(PersistenceUnitProperties.JTA_DATASOURCE, dataSource());
EntityManagerFactory emf = Persistence.createEntityManagerFactory("db1", props);
em = emf.createEntityManager();
}
public void persistAll(List list) {
int count = 0;
for (Object o : list) {
if (count == 0) {
em.getTransaction().begin();
}
em.persist(o);
count++;
if (count >= 500) {
em.getTransaction().commit();
count = 0;
}
}
if (count > 0) {
em.getTransaction().commit();
}
}
And here is my persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="db1" transaction-type="JTA">
<jta-data-source>db1</jta-data-source>
<mapping-file>orm.xml</mapping-file>
<class>com.entities.entity1</class>
<class>com.entities.entity2</class>
<class>com.entities.entity3</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<validation-mode>NONE</validation-mode>
<properties>
<property name="eclipselink.cache.size.default" value="0"/>
<property name="eclipselink.cache.shared.default" value="false"/>
<property name="eclipselink.logging.level" value="FINE"/>
</properties>
</persistence-unit>
</persistence>
The transaction is opened at the beginning and committed after persisting 500 objects, then the transaction is opened again, and so on. This process will repeat until all the objects are persisted.
The problem is that the objects are only being saved on the database after the whole list is processed, if I interrupt the execution, even if the transaction has already been committed, it doesn't save anything.
Does anyone have any idea on what I'm doing wrong?