gpt4 book ai didi

JPA:Eclipselink不尊重em.remove()

转载 作者:行者123 更新时间:2023-12-04 18:12:42 25 4
gpt4 key购买 nike

我需要删除一个实体并创建另一个实体:

@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 Persistence Services-2.3.2.v20111125-r10461

persistence.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

最佳答案

原因可能是Eclipselink如Eclipselink documentation所述在提交期间更改了操作顺序:

By default, EclipseLink does insert and update operations first, before delete operations, to ensure that referential integrity is maintained. This is the preferred approach.



您可以通过刷新(已经发现)或通过为Eclipselink设置特殊参数来更改此行为:

If you are forced to replace an object with unique constraints by deleting it and inserting a replacement, you may cause a constraint violation if the insert operation occurs before the delete operation. In this case, call setShouldPerformDeletesFirst to perform the delete operation before the insert operation.

关于JPA:Eclipselink不尊重em.remove(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10120411/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com