java - openjpa,更新,错误 'PK has non-default value'

标签 java jpa db2 websphere openjpa

我想知道是否有人遇到过这个错误并且可以解释发生了什么:

<openjpa-2.1.1-SNAPSHOT-r422266:1087028 nonfatal user error>
org.apache.openjpa.persistence.InvalidStateException: 
Primary key field com.qbe.config.bean.QBEPropertyHistory.id of com.qbe.config.bean.QBEPropertyHistory@1c710ab has non-default value. 
The instance life cycle is in PNewProvisionalState state and hence an 
existing non-default value for the identity field is not permitted. 
You either need to remove the @GeneratedValue annotation or modify the 
code to remove the initializer processing.

我有两个对象,Property 和 PropertyHistory。属性具有 PropertyHistory 的 OneToMany 列表:

@OneToMany(fetch = FetchType.LAZY, cascade=CascadeType.MERGE, orphanRemoval=false)
@JoinColumn(name="PROPERTY_NAME")
@OrderBy("updatedTime DESC")
private List<QBEPropertyHistory> history = new ArrayList<QBEPropertyHistory>();

然后像这样加载和保存 Property 对象:

public T find(Object id) {
    T t = null;
    synchronized(this) {
        EntityManager em = getEm();
        t = em.find(type, id);
        //em.close(); //If this is uncommented, fetch=LAZY doesn't work. And fetch=EAGER is too slow.
    }
    return t;
}

public T update(T t) {
    synchronized(this) {
        EntityManager em = getEm();
        em.getTransaction().begin();
        t = em.merge(t);
        em.getTransaction().commit();
        em.close();
        return t;
    }
}

在服务层中,我使用 find(id) 方法加载一个属性,实例化一个新的 PropertyHistory,将其添加到属性 prop.getHistory().add(propHist) 中,然后调用 update(prop) 并得到上述错误。

如果我在 find() 中关闭 EntityManager,错误就会消失,但这会中断延迟加载,并且 prop.getHistory() 总是返回 null。如果我设置 fetch=EAGER,它会变得慢得令人无法接受,因为有 10 条记录或 1000 条记录,我需要一次选择数千个属性对象,而 99.99% 的时间都不需要历史记录。

我无法按照错误文本的建议删除 @GeneratedValue,因为它是生成的(DB2,自动增量)。现在我想知道如何“修改代码以删除初始化程序处理”?

谢谢!

最佳答案

问题是您正在尝试跨持久性上下文 (EntityManager) 共享一个实体。您可以更改方法以采用 EntityManager 实例并使用相同的 EM 进行查找和更新操作。

关于java - openjpa,更新,错误 'PK has non-default value',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12945675/

相关文章:

java - 如何在 JBoss 7 中从一台机器向 JMS 服务器发送消息并从另一台机器接收消息

java - JpaRepository 不更新实体

java - 从 OneToMany 集合中删除时出现 EntityNotFoundException

sql - 在同一行中添加列字段值?

jdbc - 在 SQuirrel-sql 中调试 SQL 查询

java - JAX-WS (JAXB) : How to marshall java. util.Date 到 xs :anyType as xs:date instead of xs:dateTime?

java - JPA - 如果不存在则创建实体?

java - 为什么 listFiles() 也将目录列为文件?

java - JPA 多线程添加如果不存在?

sql - 获取 DB2 中所有角色和授予权限的列表