Add a Custom message for the Unique Constraints in hibernate

hibernate check unique constraint before insert
spring boot unique constraint validation
hibernate unique constraint
add constraint in hibernate
set unique constraint jpa
hibernate unique constraint not working
hibernate unique constraint error message
unique constraint entity
@Entity @Table(name="users",uniqueConstraints = {@UniqueConstraint(columnNames = {"email"})})
public class User implements Serializable {
    @Column(unique = true,name = "email")
    @NotNull(message = "{}")
    @Email(message = "{}")
    @Size(min=10, max=50)
    private String email;

    public String getEmail() { return email; }
    public void setEmail(String email) { = email; } 

I have the file which is working fine = Email is required = Enter a valid email address

can i add another field in the file like = Email already exits 

and give this to the

@Column(unique = true,name = "email",message="{}")

I know, we cannot keep message="{}" in the above line.

but how can we give "" to the above column in order to get the custom error message


Thanks in advance

User defined annotation "@Unique" in the model

@Column(unique = true,name = "email")
@Unique(message = "{}")
private String email; = Email id already exists

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import javax.validation.Constraint;
import javax.validation.Payload;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

@Target({ElementType.METHOD, ElementType.FIELD})
@Constraint(validatedBy = UserUniqueValidator.class)
public @interface Unique {
    String message();
    Class<?>[] groups() default { };
    Class<? extends Payload>[] payload() default { };

import com.User;
import com.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class UserUniqueValidator implements ConstraintValidator<Unique,String> {

    private UserService userService;

    public void initialize(Unique unique) {

    public boolean isValid(String email, ConstraintValidatorContext context) {
        if (userService != null && userService.existsByEmail(email,User.class)) {
            return false;
        return true;

public interface UserService {
    public boolean existsByEmail(String email,Class clazz);

import com.UserRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

public class UserServiceImpl extends UserRepository implements UserService  {

    public boolean existsByEmail(String email, Class clazz) {
        return super.existsByEmail(email,clazz);


public class UserRepository {
  public boolean existsByEmail(String email, Class className) {
      Criteria criteria = getSession().createCriteria(className,"userEmail");
      if(criteria.list().size() == 0){
            return false;
      return true;

Add a Custom message for the Unique Constraints in hibernate, Add a Custom message for the Unique Constraints in hibernate. spring unique constraint validation constraintvalidator custom message hibernate check unique​  /** * (Optional) Whether the column is a unique key. This is a * shortcut for the <code>UniqueConstraint</code> annotation at the table * level and is useful for when the unique key constraint * corresponds to only a single column.

In your UserRepository File

public interface UserRepository extends JpaRepository<User, Long> {
      Boolean existsByEmail(String email);

In your controller file

private UserRepository userRepository;

if(userRepository.existsByEmail(pass_email_HERE)) {
        throw new YourCustomExceptionException("CUSTOM_ERROR_MESSAGE");

Unique Field Validation Using Hibernate and Spring, Learn how to validate that a field is unique by writing a custom Hibernate validator To overcome these shortcomings, I set out to implement a different attribute (which is the error message if the constraint's isValid method  Algorithms AngularJS ansible Architecture Books CommandLine container DevOps docker English Functional Programming git golang hibernate java javascript JavaServer Faces kubebuilder kubernetes layout maven meteor minikube mongoDB neo4j NodeJS OpenShift operators postgreSQL primefaces python regex shell SO think tips Uncategorized [Intellij IDEA]

I resolve similar problem in Spring Boot I Hope It will help u.

public class ControllerExceptionHandler extends ResponseEntityExceptionHandler {

@ExceptionHandler(value = {DataIntegrityViolationException.class})
protected ResponseEntity<JSONObject> handleConflict(DataIntegrityViolationException ex, WebRequest request) {
    JSONObject result = new JSONObject();
    result.appendField("result", false);
    String errorMessage = "";

    org.hibernate.exception.ConstraintViolationException exDetail =
            (org.hibernate.exception.ConstraintViolationException) ex.getCause();

    errorMessage = fieldCnvrt(exDetail.getConstraintName()) + " birden fazla aynı değer içeremez!";

    result.appendField("message", errorMessage);
    return ResponseEntity.status(HttpStatus.NOT_ACCEPTABLE).body(result);

private String fieldCnvrt(String field) {
    switch (field) {
        case "username":
            field = "Kullanıcı Adı";
        case "email":
            field = "Email";
        case "short_name":
            field = "Kısaltımış Ad";
        case "name":
            field = "Ad";

    return field;


Chapter 6. Creating custom constraints, To create a custom constraint, the following three steps are required: Create a String message() default "{org.hibernate.validator.referenceguide.chapter06. Most other solutions that I have found use one of the following approaches to implement a unique constraint validator: Inject an EntityManager into the custom validator, or alternatively a SessionFactory. Inject a repository/DAO into the custom validator. Inject a specific service into the custom validator.

Chapter 4. Interpolating constraint error messages, Message interpolation is the process of creating error messages for violated Bean how you can plug in custom message interpolators in case the default algorithm is As of Hibernate Validator 5 (Bean Validation 1.1) it is possible to use the  I'm been trying to extend the Hibernate Validator framework by adding constraint checking for unique values (the username of a user entity for example). Following the documentation, this is what I've come up with so far:

How to add a new constraint to Hibernate Validator in a few simple , This post will be useful to those who have some interesting custom Bean Validation Step 1 - Add constraint annotation and validator public @interface ISBN { String message() default "{org.hibernate.validator.constraints. Hibernate Validator also requires an implementation of the Unified Expression Language (JSR 341) for evaluating dynamic expressions in constraint violation messages. When your application runs in a Java EE container such as WildFly, an EL implementation is already provided by the container.

JPA + Hibernate, The attribute 'uniqueConstraints' of @Table annotation can be used to apply unique constraints to the specified fields. EMPLOYEE ADD CONSTRAINT PUBLIC. getJdbcSQLException( at org.h2.message. Git - Specifying custom Git Repository and Work Tree locations · Git -  Java example to use hibernate validator to validate Java bean fields.Bean validation API 2 (JSR-380) offers some popular annotations that can be attached to each bean property for the purpose of maintaining data integrity.

  • for this solution , you must use 'find' in database , it's wrong !