gpt4 book ai didi

hibernate NonUniqueObjectException : a different object with the same identifier value was already associated with the session:

转载 作者:行者123 更新时间:2023-12-03 12:43:19 24 4
gpt4 key购买 nike

我的代码:

我正在尝试进行更新/插入。它被正确插入,唯一的问题是当我尝试更新它时会给出以下错误消息。

private String sessionType=null;
public String getAccountsDetails(List<Account> accountList) {
Session session = sessionFactory.openSession();
for (Account account : accountList) {
AccountDetails accountDetails = new AccountDetails();
accountDetails.setAccountsId(Long.parseLong(account.getId()));
accountDetails.setAccounttype(account.getAccountType().value());
Query query = session.createQuery("from QBAccounts qba where qba.accountsId=:accId");
List<AccountDetails> queryList = query.setParameter("accId", accountDetails.getAccountsId()).list();
if(queryList.size()>0){
session.update(accountDetails);
}else{
session.save(accountDetails);
}
}
session.flush();
session.beginTransaction().commit();
session.clear();
session.close();
return "Successfully data updated into table";
}

错误:
org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session: [com.trinet.mulesoft.quickbooks.dto.AccountDetails#0]
at org.hibernate.engine.StatefulPersistenceContext.checkUniqueness(StatefulPersistenceContext.java:638)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.performUpdate(DefaultSaveOrUpdateEventListener.java:305)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsDetached(DefaultSaveOrUpdateEventListener.java:246)

编辑2:

我用过了

session.merge(accountDetails)



没有错误,但它总是将数据插入数据库而不是更新。

最佳答案

打开两个 session 时出现此错误。
一个用户 session 和一个对象的另一个 session ,该对象的主键是来自用户的外键。
这样,两个 session 具有相同的主键或标识符。
我在 session.update(type) 之前通过 session.clear 解决了这个问题。
public T update(T type) {
Session session = getSession();
session.clear();
session.update( type );
session.flush();
return type;
}

关于 hibernate NonUniqueObjectException : a different object with the same identifier value was already associated with the session:,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25984658/

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