java - 为什么@Size 注释在 List 上不起作用?
问题描述
我的实体属性如下所示:
@Valid
@Size(min=1, max=16)
@ManyToMany(cascade={ CascadeType.PERSIST })
@JoinTable(name="CustomerRoles",
joinColumns={ @JoinColumn(name="CustomerId") },
inverseJoinColumns={ @JoinColumn(name="RoleId") }
)
@JsonProperty(access=JsonProperty.Access.WRITE_ONLY)
private List<Role> roles = new ArrayList<Role>();
@JsonIgnore
public List<Role> getRoles() {
return this.roles;
}
@JsonIgnore
public void setRoles(List<Role> roles) {
this.roles = roles;
}
@ApiModelProperty(notes="Roles of the customer.", required=true, value="User")
@JsonProperty("roles")
public List<String> getRolesAsStringList() {
return this.roles.stream().map(Role::getName)
.collect(Collectors.toList());
}
当我去保存实体时,我得到以下异常:
约束违规列表:[ConstraintViolationImpl{interpolatedMessage='size must be between 1 and 16', propertyPath=roles, rootBeanClass=class org.xxx.yyy.models.Customer, messageTemplate='{javax.validation.constraints.Size.message }'} ]] 有根本原因
在我保存服务之前的右行上,我打印出 customer.getRoles().size() 并且它是 = 1。
@Size 不适用于列表吗?我发现似乎表明它应该的信息。
编辑:服务方法看起来像:
public Customer createCustomer(Customer customer) throws InvalidRolesException {
System.out.println("IN1 ==> " + customer.getRoles().size());
List<String> errors = new ArrayList<String>();
customer.setRoles(customer.getRolesAsStringList().stream().map(role -> {
try {
return new Role(FindRoleByName(role), role);
}
catch (Exception e) {
errors.add(role);
return null;
}
}).collect(Collectors.toList()));
System.out.println("IN2 ==> " + customer.getRoles().size());
if (!errors.isEmpty())
throw new InvalidRolesException(errors);
System.out.println("IN3 ==> " + customer.getRoles().size());
return this.customerRepository.save(customer);
}
不要介意噪音,这只是将字符串数组按摩回角色对象......它打印出 IN3 ==> 1。
回购只是股票休眠:
public interface CustomerRepository extends JpaRepository<Customer, Long> {
}
解决方案
你真的需要这里的@ManyToMany
关系吗?这应该足够了:
@Size(min = 1, max = 16)
@JoinColumn(name = "customer_id")
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER)
private List<Role> roles;
推荐阅读
- python - 删除 Python 列表中的前导/尾随停用词
- xml - 在类型值上创建 XPath 过滤?
- javascript - 通过 Babel Loader 运行 Babel 时的行为不一致
- python - Python中是否有一种快速的方法可以按列和行分组来拆分?
- c# - 重新抛出 JsonConverter 异常的正确方法
- google-chrome-extension - 如何让我的扩展模拟鼠标中键点击
- git - 将“git status”信息添加到标准 zsh 配置文件
- python - 在字典中存储类实例对象。我怎样才能把它们弄出来?
- syntax-highlighting -
缩进问题 - reactjs - NextJS 内容页面未更新页面