Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a Custom message for the Unique Constraints in hibernate

@Entity @Table(name="users",uniqueConstraints = {@UniqueConstraint(columnNames = {"email"})})
public class User implements Serializable {
    @Column(unique = true,name = "email")
    @NotNull(message = "{NotNull.email}")
    @Email(message = "{Pattern.email}")
    @Size(min=10, max=50)
    private String email;

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

I have the message.properties file which is working fine

 NotNull.email = Email is required

 Pattern.email = Enter a valid email address

can i add another field in the message.properties file like

 Unique.email = Email already exits 

and give this Unique.email to the

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

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

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

??

Thanks in advance

like image 613
Semantic Avatar asked Mar 06 '23 03:03

Semantic


1 Answers

User defined annotation "@Unique" in the model User.java

@Column(unique = true,name = "email")
@Unique(message = "{Unique.email}")
private String email;

message.properties

Unique.email = Email id already exists

Unique.java

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;

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

UserUniqueValidator.java

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> {

    @Autowired
    private UserService userService;

    @Override
    public void initialize(Unique unique) {
        unique.message();
    }

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

UserService.java

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

UserServiceImpl.java

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

@Service
@Transactional
public class UserServiceImpl extends UserRepository implements UserService  {

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

}

UserRepository.java

public class UserRepository {
  public boolean existsByEmail(String email, Class className) {
      Criteria criteria = getSession().createCriteria(className,"userEmail");
      criteria.add(Restrictions.eq("email",email));
      if(criteria.list().size() == 0){
            return false;
      }
      return true;
  }
}
like image 94
Semantic Avatar answered May 31 '23 07:05

Semantic