简体   繁体   English

Hibernate事务引发另一个事务的异常

[英]Hibernate transaction throws exception from another transaction

I'm trying to save data using Hibernate. 我正在尝试使用Hibernate保存数据。 Everything happens within the same session. 一切都在同一会话中发生。 The logic is following : 逻辑如下:

1) Begin a transaction and try to save : 1)开始交易并尝试保存:

try
{

  session.getTransaction().begin();
  session.save(result);
  session.getTransaction().commit();
}
catch (Exception e)
{
  session.getTransaction().rollback();
  throw e;
}

2) If a new record violates integrity constraint catch an exception in the outer wrapper method, open another transaction and query more data 2)如果新记录违反完整性约束,则在外部包装器方法中捕获异常,请打开另一个事务并查询更多数据

catch (ConstraintViolationException e)
{
  if ("23000".equals(e.getSQLException().getSQLState()))
  {
    ...

    session.getTransaction().begin();
    Query query = session.createQuery("from Appointment a where a.begin >= :begin and a.end <= :end");
    query.setDate("begin", date);
    query.setDate("end", DateUtils.addDays(date, 1));

    List results = query.list();
    session.getTransaction().commit();

The problem is when the second transaction performs query.list it throws an exception that should'be been linked with the previous transaction. 问题是当第二个事务执行query.list时,它将引发一个异常,该异常应与上一个事务链接。

SQLIntegrityConstraintViolationException: ORA-00001: unique constraint SQLIntegrityConstraintViolationException:ORA-00001:唯一约束

Should I query data from another session or what's the other way to isolate two transactions from each other? 我应该从另一个会话中查询数据还是将两个事务彼此隔离的另一种方法是什么?

Thanks! 谢谢!

You should not use the same session if you get an exception, you have to close the session and use a different session for your second operation. 如果遇到异常,则不应使用相同的会话,而必须关闭该会话并为第二个操作使用其他会话。 This is given in hibernate documentation: 这在休眠文档中给出:

13.2.3 Exception Handling 13.2.3异常处理

If the Session throws an exception, including any SQLException, immediately rollback the database transaction, call Session.close() and discard the Session instance. 如果Session引发异常(包括任何SQLException),请立即回滚数据库事务,调用Session.close()并丢弃Session实例。 Certain methods of Session will not leave the session in a consistent state. 某些会话方法不会使会话保持一致状态。 No exception thrown by Hibernate can be treated as recoverable. Hibernate抛出的异常不能被视为可恢复的。 Ensure that the Session will be closed by calling close() in a finally block. 通过在finally块中调用close()来确保关闭会话。

希望Exception类是所有类型的异常的基础,因此,如果将Exception类放置在始终被捕获之前,并且将隔离其余的异常处理,则该类为例外。

Can you try to replce session.save() with session.persist method, hope this might resolve your problem. 您是否可以尝试使用session.persist方法替换session.save(),希望这可以解决您的问题。 Refer following link for more details about both methods. 有关这两种方法的更多详细信息,请参考以下链接。

What's the advantage of persist() vs save() in Hibernate? 在Hibernate中,persist()与save()的优点是什么?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM