Skip to content

Commit

Permalink
Fix 'object references an unsaved transient instance' error [ACC-1827]
Browse files Browse the repository at this point in the history
By adding FetchType.LAZY to @OnetoOne and @manytoone relations, their references are no longer automatically updated when CrudRepository.save() returns a different instance (usually when it is not yet present in the db). When fetching such an entity with an old reference, Hibernate will not find the id of the target entity and throws 'object references an unsaved transient instance' error. The problem is solved by setting the @OnetoOne or @manytoone relation manually after the other side was saved.
  • Loading branch information
NielsCW committed Jan 29, 2025
1 parent 865a54d commit 7a4eccb
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -130,14 +130,19 @@ void setupTestData() {
inbev.setVat(ORG_INBEV_VAT);
inbev = customers.save(inbev);

ORDER_1 = orders.save(new Order(xenit, address_northPole, Set.of())).getId();
var order1 = orders.save(new Order(xenit, address_northPole, Set.of()));
var order2 = orders.save(new Order(xenit));
var order3 = orders.save(new Order(inbev));

ORDER_1 = order1.getId();
ORDER_3 = order3.getId();

// address_northPole is still referencing an unsaved order1,
// update address_northPole so that its order has an id
address_northPole.setOrder(order1);

invoices.saveAll(List.of(
new Invoice(INVOICE_1, true, false, xenit,
new HashSet<>(List.of(orders.getReferenceById(ORDER_1), order2))),
new Invoice(INVOICE_1, true, false, xenit, new HashSet<>(List.of(order1, order2))),
new Invoice(INVOICE_2, false, true, inbev, new HashSet<>(List.of(order3)))
));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -129,14 +129,19 @@ void setupTestData() {
inbev.setVat(ORG_INBEV_VAT);
inbev = customers.save(inbev);

ORDER_1 = orders.save(new Order(xenit, address_northPole, Set.of())).getId();
var order1 = orders.save(new Order(xenit, address_northPole, Set.of()));
var order2 = orders.save(new Order(xenit));
var order3 = orders.save(new Order(inbev));

ORDER_1 = order1.getId();
ORDER_3 = order3.getId();

// address_northPole is still referencing an unsaved order1,
// update address_northPole so that its order has an id
address_northPole.setOrder(order1);

invoices.saveAll(List.of(
new Invoice(INVOICE_1, true, false, xenit,
new HashSet<>(List.of(orders.getReferenceById(ORDER_1), order2))),
new Invoice(INVOICE_1, true, false, xenit, new HashSet<>(List.of(order1, order2))),
new Invoice(INVOICE_2, false, true, inbev, new HashSet<>(List.of(order3)))
));
}
Expand Down

0 comments on commit 7a4eccb

Please sign in to comment.