1 回答
TA贡献1876条经验 获得超5个赞
通过在实体removeAddress中添加方法User,您可以更新表的fk address,也可以保留行:
public void removeAddress(Address address) {
address.setUser(null); // or the value you want
}
该updateUserAddress方法应该是这样的:
public void updateUserAddress() {
User user = repository.findById(1L);
List<Address> addresses = user.getAddresses();
Address address = addresses.get(0); //the address to be removed
user.removeAddress(address);
user.setAddresses(addresses);
repository.save(user);
}
用户实体:
@Entity
@Table(name = "users")
public class User {
// other fields
@OneToMany(cascade = CascadeType.ALL, mappedBy = "user", fetch=FetchType.EAGER)
@JsonManagedReference
private List<Address> addresses;
// getters, setters, constructors etc.
// the remove method
public void removeAddress(Address address) {
address.setUser(null);
}
}
地址实体:
@Entity
@Table(name = "address")
public class Address {
// other fields
@ManyToOne
@JoinColumn(name = "user_id")
@JsonBackReference
private User user;
// getters, setters, constructors etc.
}
添加回答
举报