Pankaj
Pankaj

Reputation: 97

Exception Handling in DAO layer of Spring Project with JPA

I am using Spring & JPA with Hiberate as vendor.

In DAO layer I am trying to persist entity. If duplicate exists, it throws ConstraintViolationException of Hibernate. I have written try-catch in DAO for catching the exception but it does't go to catch block at all and throws Exception to service layer. Does JPA allow to catch JDBCException in DAO layer or it'll directly throw it to upper layer?

My code looks like as follows :

public void saveEntity(SomeEntity entity) throws CustomException {
   try {
      ... do something...
      entityManager.persist(entity);
    }catch(Exception e) {
      throw new CustomException(e.getMessage());
    }
}

Here If something happens before persist it catches but if something goes wrong while persisting and JDBCException comes it doesn't.

I know that I could have avoided this situation by checking first that if record exists and if not, only then I'll save. But I want to know why JDBCException (or any database related exceptions) exceptions are not getting caught here.

Any help appreciated.

Upvotes: 0

Views: 3452

Answers (1)

Pankaj
Pankaj

Reputation: 97

I have found the reason for this.

The catch block in the DAO class is not able to catch exception because transaction commit is happening after method getting executed and so the method on which I have put @Transactional (service layer method) is catching the exception instead.

Here if I use flush() right after persist, it tries to commit right there and throws Exception which will get caught.

public void saveEntity(SomeEntity entity) throws CustomException {
   try {
      ... do something...
      entityManager.persist(entity);
      entityManager.flush(); //tries to commit here & throws ConstraintViolationException    if already exists
    }catch(Exception e) {
      throw new CustomException(e.getMessage());
    }
}

Upvotes: 1

Related Questions