I’m having trouble with bean validation in my Jakarta EE and Hibernate project. My validation method is not catching any violations even when the entity contains invalid values. Here’s the relevant code:
Validation Method:
private void validate(T entity, Class<?>... groups) {
Set<ConstraintViolation<T>> violations = EntityValidator.validateEntity(entity, groups);
if (!violations.isEmpty()) { // Always Empty!
for (ConstraintViolation<T> violation : violations) {
throw new RuntimeException(violation.getPropertyPath() + ": " + violation.getMessage());
}
}
}
EntityValidator Class:
public class EntityValidator<T> {
private static final ValidatorFactory DEC_FACTORY = Validation.byDefaultProvider()
.configure()
.buildValidatorFactory();
public static <T> Set<ConstraintViolation<T>> validateEntity(T entity, Class<?>... groups) {
Set<ConstraintViolation<T>> violations = DEC_FACTORY
.getValidator().validate(entity, groups);
return violations;
}
}
Entity Class:
@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;
}
Test Case:
User user = new User();
user.setUsername("a");
user.setPasswordHash("abc");
validate(user);
Despite setting invalid values, the validate
method doesn’t detect any violations. My project uses Jakarta 2.0.2 and Hibernate 6.0.2. How can I ensure that the bean validation catches these violations?