为什么@Size注释在列表上不起作用?



我的实体属性如下所示:

@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="大小必须介于1和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;

最新更新