(休眠)提交失败后表被更改
我是冬眠新手。我有一个事务因 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。
I'm new to hibernate. I have a transaction that fails with a HibernateException, yet the table is altered after the commit. Here is the code:
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();
}
}
EDIT: Apparently InnoDB does not rollback the transaction on a duplicate key error but only the statement. I would like the transaction to be always rolled back on ANY error.
EDIT2: Disregard this. I was using MyIsam.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
从 MyIsam 切换到 InnoDB 解决了这个问题。
Switching from MyIsam to InnoDB fixed this.