0

I have two classes with a unidirectional relationship:

@Entity
public class A {

   @OneToMany(cascade = CascadeType.ALL)
   @JoinColumn(name="fk_column")
   private List<B> bList;

   ...
}

@Entity
public class B {
   ...
}

When I do this first time:

A a = new A();
B b = new B();
a.getBList().add(b);
em.merge(a);

then a as well as b is persisted initial in the database and b has got the right foreign key to a.

But when I do this in another transaction:

A a = loadFromDatabaseByJPQLQuery(); 
B anotherB = new B();
a.getBList().add(anotherB);
em.merge(a);

then anotherB is persist indeed, but it's foreign key to a in fk_column is null.

How do I make it that the key is stored correctly?

Fireworx
  • 11
  • 5
  • I cannot figure it out from your example so I will ask, entity B has `@ManyToOne` column defined? Also on `@OneToMany` you can use the annotation's property `mappedBy` to define who is holding the relation instead of `@JoinColumn`. – alexandrum Apr 12 '17 at 18:08
  • No it is a unidirectional relationship. Ther is no @ManyToOne in B. – Fireworx Apr 12 '17 at 18:11
  • Try to add in `@JoinColumn` the property `referencedColumnName` and take a look [here](http://stackoverflow.com/questions/11244569/what-is-referencedcolumnname-used-for-in-jpa) for more info about that property. – alexandrum Apr 12 '17 at 18:24
  • No also with the `referencedColumnName` attribute it doesn't work. – Fireworx Apr 13 '17 at 07:36
  • The not working example seems exactly the same as the working example, and should be treated the same by JPA. Try turning on logging and see if what shows up; EclipseLink should insert B with a null and then update the row afterward when it processes the change to 'A''s relationship. – Chris Apr 13 '17 at 16:51

0 Answers0