0

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.

1 Answer 1

1

Validation was being executed twice, once in the service layer (where I wanted it to happen) and once when entity was persisted/merged (jpa was calling it). So I disabled it by adding this line to my persistence.xml:

<property name="javax.persistence.validation.mode" value="none"/>

Now everything works fine

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.