gpt4 book ai didi

java - 自定义 Bean 验证的 Hibernate 错误

转载 作者:行者123 更新时间:2023-12-01 09:05:19 26 4
gpt4 key购买 nike

我正在尝试创建自定义 bean 验证,因此我编写了此自定义约束:

@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 {};

}

还有一个 validator :

public class ValidPackageSizeValidator implements ConstraintValidator<ValidPackageSize, PackageSize> {

...

@Override
public boolean isValid(PackageSize value, ConstraintValidatorContext context) {
...validation login here..
}

}

此外,我希望在调用一些装饰器后立即在服务层上执行验证,因此我创建了另一个装饰器来处理此任务..

@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);
}
}
}

一切正常,但如果验证通过,hibernate 会抛出错误:

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)

我的实体使用自动生成的 id 值。

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
protected Long id;

将 Widlfly 9 与 JEE 7 结合使用。

最佳答案

验证被执行两次,一次在服务层(我希望它发生),一次在实体被持久化/合并时(jpa 调用它)。所以我通过将此行添加到我的 persistence.xml 来禁用它:

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

现在一切正常

关于java - 自定义 Bean 验证的 Hibernate 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41325520/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com