Issue
I have 2 object person and address. person is parent and address is child.
- Person : personPK , status
- Address : addressPK , person_fk, status
My repository is extending JPARepository.
personRepository.save(person);
is working fine for insert.
But when I update the person object by updating status(eg: Active) in both the tables and use personRepository.save(person);
My foreign key references(person_fk) is set as null.
My parent class :
@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<>();
...
}
And my child class :
@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;
...
}
And from my service layer I am updating it using :
personRepostiry.save(person);
Any help what I am doing wrong here?
Solution
Firstly Change:
@ManyToOne
@JoinColumn(name = "person_fk", referencedColumnName = "person_pk", nullable=false)
private Address address;
to:
@ManyToOne(targetEntity = Person.class)
@JoinColumn(name = "person_fk", referencedColumnName = "person_pk", nullable = false)
private Person person;
then change:
@OneToMany(fetch = FetchType.EAGER, mappedBy = "person",cascade = CascadeType.PERSIST)
private Set<Address> addresses = new HashSet<>();
to:
@OneToMany(fetch = FetchType.EAGER, mappedBy = "person", cascade = {CascadeType.PERSIST, CascadeType.MERGE})
private Set<Address> addresses = new HashSet<>();
and add this to your Person class:
public void addAddress(Address address) {
address.setPerson(this);
addresses.add(address);
}
then use:
person.addAddress(address);
persist(person)
or
merge(person);
Answered By - Roham Amini
Answer Checked By - Marie Seifert (JavaFixing Admin)