问题
Besides primitive types and String none of the fields of my "Declaration" entity can be validated. They're all ignored by the validator.
Issue in Hibernate tracker and Example project.
@Entity
@Table(name = "declaration")
public class Declaration {
[fields id, language, ...]
@Valid
@OneToMany(mappedBy = "declaration", fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true)
@Fetch(value = FetchMode.SUBSELECT)
private List<@Valid Child> children = new ArrayList<>();
@Valid
@Embedded
private Child embeddedChild;
}
@Entity
@Table(name = "child")
public class Child {
@ManyToOne
@JoinColumn(name = "declaration_id")
private Declaration declaration;
@NotNull
@Transient
private String alwaysAnError = null;
}
I've got 3 issues here.
1°
The entity was previously loaded and cached by Hibernate. I guess it is proxied but somehow Hibernate.isInitalized(declaration.getChildren()) returns true.
https://docs.jboss.org/hibernate/stable/orm/userguide/html_single/Hibernate_User_Guide.html#pc-contains
2°
Entities in a relationship with the "Declaration" entity are not validated.
From the entity point of view all relationships are eager. If the entity is proxied, I thought it would be validable using an "always-yes" TraversableResolver. However it doesn't work.
https://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/?v=6.0#section-validator-factory-traversable-resolver
3°
Embedded objects are not validated.
I didn't expect a proxy to restrict the access to those fields either.
https://docs.jboss.org/hibernate/stable/orm/userguide/html_single/Hibernate_User_Guide.html#_component_embedded
What is happening ?
Some kind of byte code manipulation occurs but I didn't enable byte code enhancement.
From the documentation
When lazy loaded associations are supposed to be validated it is recommended to place the constraint on the getter of the association.
This solves my issue but I didn't expect it to work that way.
Could it be possible for a properly-configured TraversableResolver to navigate through @Valid fields even if they are embedded ?
If my expectations are wrong, could someone please point me to the truth ?
来源:https://stackoverflow.com/questions/58203866/entity-proxy-children-can-not-be-validated-even-with-traversableresolver