When building relationships in JPA, how do you link a child entity to an existing parent without needlessly hitting the database for the parent's full data? Don't reach for findById if you only have the parent's ID.
repository.findById(id) always fetches the entity from the database. If you just need to set a foreign key, like when creating a LineItem and linking it to an Order, this is an unnecessary read.
Instead, use repository.getReferenceById(id). This method returns a proxy object, an entity reference, without executing a SELECT query. The database is only hit if you access a field on that proxy other than its ID.
// Assuming Order exists with ID 123
Order orderRef = orderRepository.getReferenceById(123L);
LineItem newItem = new LineItem();
newItem.setName("Awesome Widget");
newItem.setPrice(BigDecimal.valueOf(29.99));
newItem.setOrder(orderRef); // Associates without loading the full Order entity
lineItemRepository.save(newItem); // Only now is the Order ID part of the INSERT
This tiny optimization significantly reduces redundant queries and improves performance in high-volume write operations. Keep your database calls lean.
Top comments (0)