在休眠中为Unique Constraints添加Custom消息

时间:2018-05-22 11:28:21

标签: hibernate spring-mvc

@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; } 
}

我有message.properties文件正常工作

 NotNull.email = Email is required

 Pattern.email = Enter a valid email address

我可以在message.properties文件中添加另一个字段,如

 Unique.email = Email already exits 

并将此Unique.email提供给

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

我知道,我们无法在上面的行中保留message =“{Unique.email}”。

但我们怎样才能将“Unique.email”提供给上面的列以获取自定义错误消息

...

提前致谢

3 个答案:

答案 0 :(得分:1)

用户定义的注释" @ Unique"在模型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;
  }
}

答案 1 :(得分:0)

在您的UserRepository文件中

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

在您的控制器文件中

@Autowired
private UserRepository userRepository;

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

答案 2 :(得分:0)

我解决了Spring Boot中的类似问题,希望对您有所帮助。

@ControllerAdvice
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ı";
            break;
        case "email":
            field = "Email";
            break;
        case "short_name":
            field = "Kısaltımış Ad";
            break;
        case "name":
            field = "Ad";
            break;
    }

    return field;
}

}