I'm new to Hibernate
/ spring-data-jpa
and I'm trying to implement an unidirectional @OneToMany
relationship.
My parent class looks like this:
@Entity
public class Parent {
@Id
@GeneratedValue
private int id;
@OneToMany(fetch = EAGER)
@JoinColumn(name = "parent_id")
private List<Child> children;
}
And my child class:
@Entity
public class Child {
@Id
@GeneratedValue
private int id;
private String name;
}
Now I want to persist a new child via
Child newChild = new Child();
newChild.setName("child_1");
this.parentService.findParentByParentId(1).getChildren().add(newChild);
this.childService.saveChild(newChild);
but when I have a look into my database, the foreign key in child table is not set:
-----------------------------------------
| id | name | parent_id |
-----------------------------------------
| 1 | child_1 | NULL |
-----------------------------------------
Any suggestions about what's going wrong here? Thanks!
I've looked at the mapping and there's nothing wrong with it. I've even compared with some code I use to run JPA workshops and yours should work.
I would bet that the problem is the place where you start the transaction. The transaction should start in the method that executes the code
Otherwise JPA's unit of work won't see that you've added a child in the parent.
I strongly suggest you to read the section in the spring docs that explains the declarative transaction management, otherwise know that you'll spend days in despair trying to figure out why it doesn't work.