I'm trying to create a custom bean validation, so I write this custom constraint:
@Documented
@Constraint(validatedBy = ValidPackageSizeValidator.class)
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface ValidPackageSize {
String message() default "{br.com.barracuda.constraints.ValidPackageSize}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
And a validator:
public class ValidPackageSizeValidator implements ConstraintValidator<ValidPackageSize, PackageSize> {
...
@Override
public boolean isValid(PackageSize value, ConstraintValidatorContext context) {
...validation login here..
}
}
Also, I wanted the validation to be performed on the service layer just after some decorators are called, so I created an another decorator to handle this task..
@Decorator
public abstract class ConstraintsViolationHandlerDecorator<T extends AbstractBaseEntity> implements CrudService<T> {
@Any
@Inject
@Delegate
CrudService<T> delegate;
@Inject
Validator validator;
@Override
@Transactional
public T save(T entity) {
triggerValidations(entity);
return delegate.save(entity);
}
private void triggerValidations(T entity) {
List<String> errorMessages = validator.validate(entity).stream()
.map(ConstraintViolation::getMessage)
.collect(Collectors.toList());
if (!errorMessages.isEmpty()) {
throw new AppConstraintViolationException(errorMessages);
}
}
}
Everything works, but if validations pass, hibernate throws an error:
ERROR [default task-6] (AssertionFailure.java:50) - HHH000099: an assertion failure occurred (this may indicate a bug in Hibernate, but is more likely due to unsafe use of the session): org.hibernate.AssertionFailure: null id in br.com.barracuda.model.entities.impl.PackageSize entry (don't flush the Session after an exception occurs)
My entities use auto-generated id
values.
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
protected Long id;
Using Widlfly 9 with JEE 7.