Stack: java 17, spring boot, hibernate 6, postgres
Suppose we have a user entity with two unique fields - username and email.
When I try to create a new user with session.persist(userEntity), it throws a org.hibernate.exception.ConstraintViolationException, which is of course correct.
The exception contains all information for the programmer to see what's wrong, but, I'm trying to display a user-friendly error to the user (web UI), not an exception message.
The only thing that comes to my mind is to check each field explicitly, something like:
boolean emailExists = session.createQuery("select 1 from User where email = :email")
.setParameter("email", user.getEmail())
.uniqueResultOptional()
.isPresent();
if (emailExists) {
// handle email already exists
}
boolean usernameExists = session.createQuery("select 1 from User where username = :username")
.setParameter("username", user.getUsername())
.uniqueResultOptional()
.isPresent();
if (usernameExists){
// handle username already exists
}
session.persist(user);
The code above works, but it doesn't look like the ideal solution because:
- we talk to the database (up to) 3 times instead of only once
- duplication of business logic, we've already created unique database indexes and annotated our entities with
@Column(unique=true), adding another explicit check for uniqueness seems kinda... wrong
Thanks in advance ✌️