JPA更新父母子女

时间:2016-10-12 08:43:13

标签: java hibernate jpa spring-boot

我有2个对象人和地址。人是父母,地址是孩子。

  • 人:personPK,状态
  • 地址:addressPK,person_fk,status

我的存储库正在扩展JPARepository。 personRepository.save(person); 插入工作正常。 但是当我通过更新两个表中的状态(例如:Active)更新person对象并使用personRepository.save(person);我的外键引用(person_fk)被设置为null。

我的父班:

@Entity
@DynamicUpdate
@Table(name = "person")
public class Person {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="person_pk", nullable=false)
    private Long personPK;
    @OneToMany(fetch = FetchType.EAGER, mappedBy = "person",cascade = CascadeType.PERSIST)
    private Set<Address> addresses = new HashSet<>();
    ...
}

我的孩子班:

@Entity
@DynamicUpdate
@Table(name = "address")
public class Address {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "address_pk")
    private Long addressPK;
    @ManyToOne
    @JoinColumn(name = "person_fk", referencedColumnName = "person_pk", nullable=false)
    private Address address;
    ...
}

从我的服务层我将使用以下方式更新它: personRepostiry.save(person);

我在这里做错了什么帮助?

1 个答案:

答案 0 :(得分:4)

首先改变:

@ManyToOne
@JoinColumn(name = "person_fk", referencedColumnName = "person_pk", nullable=false)
private Address address;

到:

@ManyToOne(targetEntity = Person.class)
@JoinColumn(name = "person_fk", referencedColumnName = "person_pk", nullable = false)
private Person person;

然后改变:

@OneToMany(fetch = FetchType.EAGER, mappedBy = "person",cascade = CascadeType.PERSIST)
private Set<Address> addresses = new HashSet<>();

到:

@OneToMany(fetch = FetchType.EAGER, mappedBy = "person", cascade = {CascadeType.PERSIST, CascadeType.MERGE})
private Set<Address> addresses = new HashSet<>();

并将其添加到Person类:

public void addAddress(Address address) {
    address.setPerson(this);
    addresses.add(address);
}

然后使用:

person.addAddress(address);
persist(person)

merge(person);