@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”,以获取自定义错误消息

? ?

预先感谢

#1 楼

在您的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 楼

模型User.java

@Column(unique = true,name = "email")
@Unique(message = "{Unique.email}")
private String email;
中用户定义的注释“ @Unique”
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;
  }
}


评论


对于此解决方案,您必须在数据库中使用“查找”,这是错误的!

– saeedeh
19年7月7日在12:14

#3 楼

我解决了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;
}


}