【发布时间】:2014-09-20 19:35:06
【问题描述】:
@Autowired
private SessionFactory sessionFactory;
public String getAccountsDetails(List<Account> accountList) {
Session session = sessionFactory.openSession();
for (Account account : accountList) {
int i = 0;
AccountDetails accountDetails = new AccountDetails();
accountDetails.setAccountsId(Long.parseLong(account.getId()));//LINE no -20
accountDetails.setName(account.getName());
accountDetails.setSubAccount(account.getAccountSubType());
session.saveOrUpdate(accountDetails);
if (++i % 20 == 0) {
session.flush();
session.clear();
}
}
session.getTransaction().commit();
session.close();
}
输出:
即使 db 中没有数据,它也会始终运行更新。
Hibernate: update name=?, subaccount=? where accounts_id=?
....
如果我在 LINE no-20 中评论帐户 id,它总是运行插入。
休眠:插入表测试... ....
dto 类:
@Entity
@Table(name="test")
public class AccountDetails{
@Id
@GeneratedValue
@Column(name = "accounts_id")
private Long accountsId;
@Column(name = "name")
private String name;
@Column(name = "subaccount")
private String subAccount;
}
查询: 甲骨文数据库:
create table test (accounts_id NUMBER(10) NOT NULL PRIMARY KEY,
name VARCHAR(100),
subaccount VARCHAR(100)
)
我的要求是如果数据库中没有数据则插入,否则更新。
编辑
我在我的 dto 中创建了一个新字段:
@Version
@Column(name = "version")
private long version;
并在 db 中创建了一个列作为版本号 (100)。每当我运行应用程序时,它总是首先运行一个 updte 语句,然后它抛出 StaleObjectStateException 为:
Hibernate: update test set accountsubtype=?, accounttype=?, acctnum=?, active=?, currentbalance=?, currentbalancewithsubaccounts=?, description=?, fullyqualifiedname=?, name=?, subaccount=?, version=? where accounts_id=? and version=?
ERROR 2014-09-22 11:57:25,832 [[qbprojects].connector.http.mule.default.receiver.04] org.hibernate.event.def.AbstractFlushingEventListener: Could not synchronize database state with session
org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect): [com.trinet.mulesoft.quickbooks.dto.AccountDetails#63]
at org.hibernate.persister.entity.AbstractEntityPersister.check(AbstractEntityPersister.java:1932)
at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:2576)
【问题讨论】:
-
如果 ID 为 null,Hibernate 将保存,否则将更新。
标签: hibernate