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

第一个定义

简单地说,我有两个实体,第一个是用户,第二个是地址,每个用户可以有一个或多个地址。这意味着,我想要用户和地址之间的双向 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 层。


qq_笑_17
浏览 104回答 1
1回答

慕运维8079593

通过在实体removeAddress中添加方法User,您可以更新表的fk address,也可以保留行:public void removeAddress(Address address) {&nbsp; &nbsp; address.setUser(null); // or the value you want}该updateUserAddress方法应该是这样的:public void updateUserAddress() {&nbsp; &nbsp; User user = repository.findById(1L);&nbsp; &nbsp; List<Address> addresses = user.getAddresses();&nbsp; &nbsp; Address address = addresses.get(0); //the address to be removed&nbsp; &nbsp; user.removeAddress(address);&nbsp;&nbsp; &nbsp; user.setAddresses(addresses);&nbsp; &nbsp; repository.save(user);}用户实体:@Entity@Table(name = "users")public class User {&nbsp; &nbsp; // other fields&nbsp; &nbsp; @OneToMany(cascade = CascadeType.ALL, mappedBy = "user", fetch=FetchType.EAGER)&nbsp; &nbsp; @JsonManagedReference&nbsp; &nbsp; private List<Address> addresses;&nbsp; &nbsp; // getters, setters, constructors etc.&nbsp; &nbsp; // the remove method&nbsp; &nbsp; public void removeAddress(Address address) {&nbsp; &nbsp; &nbsp; &nbsp; address.setUser(null);&nbsp; &nbsp; }}地址实体:@Entity@Table(name = "address")public class Address {&nbsp; &nbsp; // other fields&nbsp; &nbsp; @ManyToOne&nbsp; &nbsp; @JoinColumn(name = "user_id")&nbsp; &nbsp; @JsonBackReference&nbsp; &nbsp; private User user;&nbsp; &nbsp; // getters, setters, constructors etc.}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java