我需要在Spring Boot应用程序中使用rest api部分更新实体,但出现错误。下面是代码
帐户实体
@Data
@Entity
@Table(name = "accounts")
@EqualsAndHashCode(callSuper = true)
public class Account implements Serializable {
private Integer tcgId;
private String emailAddress;
@Transient
private String password;
private String passwordHash;
@Transient
List<ClientCategory> categories;
@NotNull
@ApiModelProperty(required = true)
@Enumerated(EnumType.STRING)
private AccountType type;
@NotEmpty
@ApiModelProperty(required = true)
private String firstName;
@NotEmpty
@ApiModelProperty(required = true)
private String lastName;
private Boolean active = false;
@NotNull
@ApiModelProperty(required = true)
@Enumerated(EnumType.STRING)
private PhoneContactPreference phoneContactPreference;
private String profilePictureUrl;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, orphanRemoval = true)
@JoinColumn(name = "accountId", nullable = false)
private List<AccountRole> accountRoles;
@OneToMany(orphanRemoval = true, cascade = CascadeType.ALL)
@JoinColumn(name = "accountId", nullable = false)
private List<AccountPhoneNumber> phoneNumbers;
public enum AccountType {
ACCOUNT, CONTACT
}
public enum PhoneContactPreference {
CALL, TEXT;
}
}
下面是我的AccountRole实体
@Data
@Entity
@Table(name = "accountRoles")
public class AccountRole {
@Id
private Integer id;
@ManyToOne
@JoinColumn(name = "role")
private StretchRole role;
private Integer clientId;
}
下面是更新帐户的代码
Account currentAccount=accountService.getAccountById(account.getId());
currentAccount.setAccountRoles(account.getAccountRoles());
currentAccount.setPhoneContactPreference(account.getPhoneContactPreference());
currentAccount.setFirstName(account.getFirstName());
currentAccount.setLastName(account.getLastName());
return accountService.save(currentAccount);
运行此代码时,出现以下错误
Caused by: org.hibernate.HibernateException: A collection with cascade="all-delete-orphan" was no longer referenced by the owning entity instance:accountRoles
如果我直接在帐户上调用save方法,虽然效果很好,但是它将覆盖Account对象中没有的其他具有null / false的值。