According to this fabulous article by Thorben Janssen a bidirectional association for @OneToMany works like this:
Item item3 = new Item();
item3.setName("Third Item");
item3.setOrder(order);
em.persist(item3);
order = em.find(PurchaseOrder.class, orderId);
order.getItems().add(item3);
In other words,
- Persist the owner of the @ManyToOne relationship
- Just add the owner to the @OneToMany entity, you don't even need to call save() a second time
Now, why is that? I implemented this and played around with some tests just to get this right. For me personally, this is highly obfuscated hibernate magic and this behavior does not make sense.
This is why I want to dive deeper into how Hibernate works so I'm trying to understand what exactly is happening here. I know the entities are tied to the hibernate persistence layer but from here on my knowledge gets a bit wonky.