Solution: setar id = null
The code saves 10 times if it runs on the Tomcat server, but if it runs on Glassfish it only adds one time.
<?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="default" transaction-type="RESOURCE_LOCAL">
<class>entities.Secao</class>
<class>entities.Funcionario</class>
<class>entities.Unidade</class>
<class>entities.Patrimonio</class>
<class>entities.Descricao</class>
<class>entities.Classificacao</class>
<validation-mode>AUTO</validation-mode>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost/patrimonio" />
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password" value="root" />
<property name="hibernate.hbm2ddl.auto" value="update" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
</properties>
</persistence-unit>
public void save() {
int i = 0;
EntityManager em = JpaUtil.getEntityManager();
while (i < 10) {
em.merge(item);
i = i + 1;
}
item = new Item();
}
JPAUtil class:
package persistence;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import org.hibernate.Session;
public class JpaUtil {
private static final String PERSISTENCE_UNIT_NAME = "default";
private static ThreadLocal<EntityManager> manager = new ThreadLocal<EntityManager>();
private static EntityManagerFactory factory;
private JpaUtil() {
}
public static boolean isEntityManagerOpen() {
return JpaUtil.manager.get() != null && JpaUtil.manager.get().isOpen();
}
public static EntityManager getEntityManager() {
if (JpaUtil.factory == null) {
JpaUtil.factory = Persistence
.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
}
EntityManager em = JpaUtil.manager.get();
if (em == null || !em.isOpen()) {
em = JpaUtil.factory.createEntityManager();
JpaUtil.manager.set(em);
}
return em;
}
public static void evictCache(EntityManager em, String region) {
((Session) em.getDelegate()).getSessionFactory().getCache()
.evictQueryRegion(region);
}
public static void closeEntityManager() {
EntityManager em = JpaUtil.manager.get();
if (em != null) {
EntityTransaction tx = em.getTransaction();
if (tx.isActive()) {
tx.commit();
}
em.close();
JpaUtil.manager.set(null);
}
}
public static void closeEntityManagerFactory() {
closeEntityManager();
JpaUtil.factory.close();
}
}