我的实体属性如下:
@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> {
}
答案 0 :(得分:0)
您真的需要这里的@ManyToMany
关系吗?这应该足够了:
@Size(min = 1, max = 16)
@JoinColumn(name = "customer_id")
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER)
private List<Role> roles;