Safari
Safari

Reputation: 11935

Java JPA handle a 'create' with unique constraint violation

I'm using SpringBoot and JPA (with Hibernate).

We can suppose that on an entity I have some unique constraints (for example, an User entity with e-mail as constraint).

When I will receive a "create" request, in case of the resource already exists, I have to return the primary-key (for example an ID, not the e-mail) of the resource that already exists.

What's the best practice to have this?

I would like to avoid 2 queries (one to check if exists and one to create), is it possible this?

Upvotes: 2

Views: 1364

Answers (1)

Forketyfork
Forketyfork

Reputation: 7810

JPA doesn't really provide any APIs for unique constraint violation analysis. Unique constraint violation is a low level database-spiecific error that usually only contains table and field information. There's just not enough data to propagate it to the business level (to get entity and id information).

The best practice I know of is doing a manual check if an entity with such field value already exists. Unique constraint should of course still be in place just for a very rare case of concurrent inserts.

For example, if you use Spring Data JPA, you could get an id of an existing user with the following repository query:

@Query("SELECT u.id FROM User u WHERE u.email = :email")
Long getUserIdByEmail(@Param("email") String email);

Upvotes: 2

Related Questions