Метод проверки:
Код: Выделить всё
private void validate(T entity, Class... groups) {
Set violations = EntityValidator.validateEntity(entity, groups);
if (!violations.isEmpty()) { // Always Empty!
for (ConstraintViolation violation : violations) {
throw new RuntimeException(violation.getPropertyPath() + ": " + violation.getMessage());
}
}
}
Код: Выделить всё
public class EntityValidator {
private static final ValidatorFactory DEC_FACTORY = Validation.byDefaultProvider()
.configure()
.buildValidatorFactory();
public static Set validateEntity(T entity, Class... groups) {
Set violations = DEC_FACTORY
.getValidator().validate(entity, groups);
return violations;
}
}
Код: Выделить всё
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long userId;
@Column(name = "username", nullable = false, unique = true)
@Size(min = 5, max = 15, message = "{username.size}")
@Pattern(regexp = "^[a-zA-Z0-9._-]{5,15}$", message = "{username.pattern}")
private String username;
@Column(name = "password_hash")
@Pattern(regexp = "^(?=.*[0-9]).{8,}$", message = "{password.pattern}")
private String passwordHash;
}
Код: Выделить всё
User user = new User();
user.setUsername("a");
user.setPasswordHash("abc");
validate(user);
Подробнее здесь: https://stackoverflow.com/questions/788 ... -hibernate