我使用 spring boot 2.1.0.BUILD-SNAPSHOT。我创建了一个自定义注释:
@Target({ElementType.TYPE, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = UniqueUserNameValidator.class)
@Documented
public @interface UniqueUserName {
String message() default "{truyenmvc.uName.UniqueUserName.message}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
和验证:
public class UniqueUserNameValidator implements ConstraintValidator<UniqueUserName, String> {
private final UserService userServicel;
@Autowired
public UniqueUserNameValidator(UserService userServicel) {
this.userServicel = userServicel;
}
@Override
public void initialize(UniqueUserName constraintAnnotation) {
}
@Override
public boolean isValid(String userName, ConstraintValidatorContext constraintValidatorContext) {
return userName != null && !userServicel.checkUserNameExits(userName);
}
}
在实体
@Entity
@Table(schema = "", uniqueConstraints = {@UniqueConstraint(columnNames = {"uEmail"}),
@UniqueConstraint(columnNames = {"uDname"}), @UniqueConstraint(columnNames = {"uName"})})
@Data
@NoArgsConstructor
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "uID", unique = true, nullable = false)
private Long uID;
@NotEmpty(message = "{truyenmvc.uName.empty.message}")
@UniqueUserName
@Column(name = "uName", unique = true, nullable = false, length = 30)
private String uName;
}
谁能告诉我错误在哪里。以及如何克服它?谢谢!
心有法竹
隔江千里
相关分类