简单地说,我有两个实体,第一个是用户,第二个是地址,每个用户可以有一个或多个地址。这意味着,我想要用户和地址之间的双向 OneToMany 关系。
我有一个具有 3 个地址的用户(具有 3 个地址列表的用户),当我更新用户并删除一些地址(具有 2 个地址列表的用户)时,保存用户后,地址的 fk 不会更新。
我预计更新后我的新用户有 2 个地址,但地址并未更改。
简而言之:当我从用户更新地址表的列表时,地址表的 fk 没有更新。
@Entity
@Table(name = TABLE_NAME)
public class User {
public static final String TABLE_NAME = "User";
//Some Fields Like ID , name ,...
@OneToMany(cascade = CascadeType.ALL, mappedBy = "user")
@JsonManagedReference
private List<Address> addresses;
public List<Address> getAddresses() {
return addresses;
}
public void setAddresses(List<Address> addresses) {
this.addresses = addresses;
}
}
地址实体(仅写入用户字段)
@Entity
@Table(name = TABLE_NAME)
public class Address {
public static final String TABLE_NAME = "ADDRESS";
//Some Fields Like ID , name ,...
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "user_id")
@JsonBackReference
private User user;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
服务等级
@Service
public class UserService
@Autowired
UserRepository repository;
public updateUserAddress() {
//Get User With Id of 1
User user = repository.findById(1L);
//Get Addresses
List<Address> addresses = user.getAddresses();
//Delete One Address From List
addresses.remove(0);
//Set New Address to User Entity
user.setAddresses(addresses);
//Save User
repository.save(user)
//It doesn't work (List of Address of user is the same and not changed)
}
顺便说一句,我使用 Spring-data-jpa 和 Hibernate 作为 DAO 层。
慕运维8079593
相关分类