我有一个带有类型参数的自定义类,它不会被约束验证器调用。有没有办法为类型参数调用验证器?
SpringController.java
@ResponseBody
@RequestMapping(method = RequestMethod.POST)
public EntityCollection<MyEntity> processData(
@Valid @RequestBody EntityCollection<MyEntity> entityRequestSet
, BindingResult bindingResult) throws Exception {
if(bindingResult.hasErrors())
{
// Problem here is that bindingResult has no errors, even though MyEntity
// has nulls in it. If I use just MyEntity as RequestBody instead of
// EntityCollection<MyEntity>, then the bindingResult has errors in it
// for fields with nulls
MethodParameter parameter = new MethodParameter(this.getClass()
.getMethod(new Object(){}.getClass().getEnclosingMethod().getName(),
EntityCollection.class, BindingResult.class), 0);
throw new MethodArgumentNotValidException(parameter, bindingResult);
}
return null;
}
EntityCollection.java
public class EntityCollection<MyEntity> extends GenericCollectionEntity<MyEntity> {
public EntityCollection() {
super();
}
public EntityCollection(
Collection<MyEntity> entities) {
super(entities);
}
}
GenericCollectionEntity.java
public abstract class GenericCollectionEntity<T> implements Serializable {
private static final long serialVersionUID = 1L;
public GenericCollectionEntity() {
super();
}
public GenericCollectionEntity(Collection<T> entities) {
super();
this.entities = entities;
}
protected Collection<T> entities;
public Collection<T> getEntities() {
return entities;
}
public void setEntities(Collection<T> entities) {
this.entities = entities;
}
}
MyEntity.java
@Entity
public class MyEntity implements Serializable {
private static final long serialVersionUID = 1L;
@Valid
@EmbeddedId
private EntityKey key;
// getters & setters
}
EntityKey.java
@Embeddable
public class EntityKey implements Serializable {
private static final long serialVersionUID = 1L;
@NotNull
@Column(name = "ID")
private String id;
// ommitted other fields
//getters & setters
}
答案 0 :(得分:0)
我的不好,我无法对基础知识进行思考。我刚刚在抽象实体的字段中添加了@Valid
,它开始验证集合。
<强> GenericCollectionEntity.java 强>
@Valid
protected Collection<T> entities;