andreybavt
andreybavt

Reputation: 1321

Hibernate transaction throws exception from another transaction

I'm trying to save data using Hibernate. Everything happens within the same session. The logic is following :

1) Begin a transaction and try to save :

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

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.

SQLIntegrityConstraintViolationException: ORA-00001: unique constraint

Should I query data from another session or what's the other way to isolate two transactions from each other?

Thanks!

Upvotes: 0

Views: 2247

Answers (3)

Learner
Learner

Reputation: 21393

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

If the Session throws an exception, including any SQLException, immediately rollback the database transaction, call Session.close() and discard the Session instance. Certain methods of Session will not leave the session in a consistent state. No exception thrown by Hibernate can be treated as recoverable. Ensure that the Session will be closed by calling close() in a finally block.

Upvotes: 1

srinivasan Elangovan
srinivasan Elangovan

Reputation: 44

Can you try to replce session.save() with session.persist method, hope this might resolve your problem. Refer following link for more details about both methods.

What's the advantage of persist() vs save() in Hibernate?

Upvotes: 0

srinivasan Elangovan
srinivasan Elangovan

Reputation: 44

Hope the Exception class is base for all types of exceptions, hence if it is placed before it will be catched always and rest of the exception handling is isolated.

Upvotes: 0

Related Questions