我是新来的冬眠。我有一个因 HibernateException 而失败的事务,但在提交后表已更改。这是代码:
public StoreResult store(Entry entry)
{
Session session = HibernateUtility.getSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
try
{
String id;
if (entry.getStatus() == Entry.Status.PUBLISHED)
{
id = TitleToURLConverter.convert(entry.getTitle());
}
else
{
id = "temp_";
}
if (entry.getId() == null)
{
entry.setId(id);
session.save(entry);
}
else
{
session.update(entry);
session.createQuery("update Entry set id = :newId where id = :oldId")
.setString("newId", id)
.setString("oldId", entry.getId())
.executeUpdate();
session.refresh(entry);
}
transaction.commit();
return StoreResult.SUCCESS;
}
catch (RuntimeException e)
{
transaction.rollback();
if (e instanceof ConstraintViolationException) return StoreResult.DUPLICATE_ID;
throw e;
}
finally
{
session.close();
}
}
编辑:显然 InnoDB 不会回滚重复键错误的事务,而只会回滚语句。我希望事务总是在出现任何错误时回滚。
EDIT2:忽略这一点。我正在使用 MyIsam。