Vlad
Vlad

Reputation: 652

Can't catch exception from Hibernate

ClientEntity clientEntity;
try {
    clientEntity = entityManager.getReference(ClientEntity.class, clientId);
}
catch (EntityNotFoundException ex){
    System.out.println("Wrong client id: there are no client with such id.");
    return;
}

I sent the wrong parameter value. In the database there is certainly no such client (with id = 6, for example). But catch {} didn't work.

From getReference docs:

If the requested instance does not exist in the database, the EntityNotFoundException is thrown when the instance state is first accessed. (The persistence provider runtime is permitted to throw the EntityNotFoundException when getReference is called.)

But in the debugger we can see that EntityNotFoundException occurs. What am I doing wrong?

debugger

Upvotes: 0

Views: 1248

Answers (1)

v.ladynev
v.ladynev

Reputation: 19956

You miss this

the EntityNotFoundException is thrown when the instance state is first accessed

You don't access the entity state in your code.

A debugger access the entity to show it properties.

getReference() is not a suitable method to check entity existence.

You can use something like this (need to be rewritten for JPA): Hibernate: check if object exists

Upvotes: 4

Related Questions