首页 > 解决方案 > 为什么@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> {
}

标签: javaspringspring-boot

解决方案


你真的需要这里的@ManyToMany关系吗?这应该足够了:

@Size(min = 1, max = 16)
@JoinColumn(name = "customer_id")
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER)
private List<Role> roles;

推荐阅读