2

I have 2 tables with one-to-many relation on the owner class (Person) and many-to-one on the child class (Email)

My problem is that in the child class' foreign key is (person_id) is always null when I want to save my Person object. I tried different things using other questions' answers, but no luck.

I would like to solve this in an annotation approach, if it is possible.

Person Class:

@Entity
@Table(name="PERSON")
public class Person {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQ_PERSON")
    @SequenceGenerator(name="SEQ_PERSON", sequenceName="SEQ_PERSON", allocationSize=1)
    @Column(name = "person_id")
    private Long personId;

    @OneToMany(mappedBy="person", cascade=CascadeType.ALL)
    private List<Email> email;

    // getters and setters

}

Email class:

@Entity
@Table(name="EMAIL")
public class Email{

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQ_EMAIL")
    @SequenceGenerator(name="SEQ_EMAIL", sequenceName="SEQ_EMAIL", allocationSize=1)
    @Column(name = "email_id")
    private Long emailId;

    @ManyToOne
    @JoinColumn(name="person_id", referencedColumnName="person_id", insertable = true)
    private Person person;

    // getters and setters

}

I get no exception / errors when I use this.

When I change the JoinColumn to @JoinColumn(name="person_id", referencedColumnName="person_id", nullable = false, updatable = false, insertable = true) then I get this error: org.hibernate.PropertyValueException: not-null property references a null or transient value: com.test.Email.person

I tried to change the Person's email setter like this, nothing changed:

public synchronized void setEmail(List<Email> email) {

   this.email=email;
   for(Email em: email) {
      em.setPerson(this);
   }
}

source

I have a Person object, with 2 emails (as a test object to save, every column is filled, except the FK in Email table), do I have to set the FK everytime manually? (it doesn't look good, if I have multiple one-to-many variables)

Edit: I tried this Which is working, but my problem with that if I have a very deep data structure with a lot of One-To-Many relations, I have to implement this to every variable and then save.. So, is there a better solution with pure annotations / getters-setters ?

Shephard
  • 117
  • 1
  • 14
  • Also tried [this](https://stackoverflow.com/questions/14592968/open-jpa-saving-onetomany-foreign-key-not-set?fbclid=IwAR3LoiLmzTUTYDGfa5r041OUxYuZny2PtbJHGlup7sQV-rURR81M_-4ashc) – Shephard Feb 02 '22 at 08:00
  • This answer maybe can help you :D https://stackoverflow.com/a/48883398 – Wansoft Sep 29 '22 at 18:25

0 Answers0