0

I have dao layer:

@Transactional
public class DatabaseCollectionDao implements IDatabaseCollectionDao {

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public void create(Collection collection) {
           entityManager.persist(collection);
    }
}

It works correctly but:

  1. When database isn't available I have SocketException.
  2. When database contains a duplicate key I have SQLIntegrityConstraintViolationException

I am trying to try/catch it inside create method:

@Override
    public void create(Collection collection) {
           try{
               entityManager.persist(collection);
           } catch (SQLIntegrityConstraintViolationException e){
               //do smth
           }
    }

But Intellij says that It is never thrown.
When I try to try/catch Exception i have UnexpectedRollbackException.

How to handle exceptions using JPA entityManager?

update: An attempt to remove @Transactional gave nothing

P.S. To be sure i tried to try/catch it in higher layers. I don't know what i can try more to solve it.

21
  • entity.persist(entity); - is this code correct? Commented Feb 28, 2019 at 0:49
  • Yes, It works correctly. But when I stop db and try to send request or persist one more time this entity(with the same id) I have a such problem Commented Feb 28, 2019 at 0:55
  • Maybe you are thinking of Entitymanager::persist ? docs.oracle.com/javaee/7/api/javax/persistence/… Commented Feb 28, 2019 at 1:05
  • oh, sorry, of course. entityManager.persist(entity); Commented Feb 28, 2019 at 1:08
  • Please show the relevant portion of your statcktrace Commented Feb 28, 2019 at 1:12

1 Answer 1

1

create customException handler extend ResponseEntityExceptionHandler . @ExceptionHandler(ConstraintViolationException::class) fun handleConstraintViolation(ex: ConstraintViolationException, request: WebRequest): ResponseEntity {} this kotlin snippet u can convert to java easily –

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.