我需要删除一个实体并创建另一个:
@Stateless
public class StatelessBean {
@PersistenceUnit(unitName = "Unit001")
EntityManagerFactory emf;
protected void test() {
EntityManager em = emf.createEntityManager();
MyObj obj1 = em.find(MyObj.class, 100);
MyObj obj2 = new MyObj();
obj2.setKey("the same unique key as in obj1");
em.remove(obj1);
// em.flush();
em.persist(obj2); // works fine when flush() is uncommented
em.close();
}
}
如果我留下em.flush()
评论,那么我得到com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException
(新旧对象具有相同的键值)
这种异常行为的原因可能是什么?
服务器:Glassfish 3.1.2
Eclipse 持久性服务 - 2.3.2.v20111125-r10461
持久性.xml:
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
<persistence-unit name="Unit001">
<jta-data-source>jdbc/Unit001DS</jta-data-source>
<properties>
<property name="eclipselink.logging.level" value="INFO"/>
<property name="eclipselink.target-database" value="MySQL"/>
</properties>
</persistence-unit>
</persistence>
连接池:
${ASADMIN} --port ${DOMAIN_ADMIN_PORT} create-jdbc-connection-pool --datasourceclassname com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource --restype javax.sql.ConnectionPoolDataSource --property "User=user:Password=pass:URL=jdbc\:mysql\://${DB_ADDRESS}/db" Unit001DS
${ASADMIN} --port ${DOMAIN_ADMIN_PORT} create-jdbc-resource --connectionpoolid Unit001DS jdbc/Unit001DS