为了账号安全,请及时绑定邮箱和手机立即绑定

当孩子更新时如何更新jpa中双向关系所有者的fk

当孩子更新时如何更新jpa中双向关系所有者的fk

qq_笑_17 2023-07-19 16:02:30
第一个定义简单地说,我有两个实体,第一个是用户,第二个是地址,每个用户可以有一个或多个地址。这意味着,我想要用户和地址之间的双向 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")@JsonManagedReferenceprivate 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")@JsonBackReferenceprivate User user;public User getUser() {    return user;}public void setUser(User user) {    this.user = user;}}服务等级@Servicepublic class UserService@AutowiredUserRepository 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 层。
查看完整描述

1 回答

?
慕运维8079593

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.

}


查看完整回答
反对 回复 2023-07-19
  • 1 回答
  • 0 关注
  • 103 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信