nmartins
nmartins

Reputation: 185

Spring Data JPA/Hibernate handling associations

I need based on parameter retrieve or not some associations from an entity. In the bellow example I need to get the records list only if a parameter is passed through my api. Can you recommend a way of achieving this using hibernate/spring data? I'm looking for the most clean and spring data-like approach.

public class Customer {
  private UUID id;

  @OneToMany(mappedBy = "customer")

  private List<Record> records = new ArrayList<>();
}

public class Record {
    private UUID id;

    @Column(name = "customer_id", length = 36, columnDefinition = "varchar(36)", nullable = false)
    private UUID customerId;
    
    @JoinColumn(name = "customer_id", insertable = false, updatable = false)
    private Customer customer;
}

My Repository is empty:

public interface CustomerRepository extends JpaRepository<Customer, UUID> {

}

On my service I'm doing something like:

Customer customer = customerRepository.findById(customerId).orElseThrow(() -> new CustomerNotFoundException("customerId", customerId));

But what I would like to do is something like:

if (showRecords) {
    Customer customer = customerRepository.findById(customerId).orElseThrow(() -> new CustomerNotFoundException("customerId", customerId));
} else {
    Customer customer = customerRepository.findByIdWithoutAssociations(customerId).orElseThrow(() -> new CustomerNotFoundException("customerId", customerId));
}

Upvotes: 0

Views: 225

Answers (1)

gtiwari333
gtiwari333

Reputation: 25146

How about using the base findById to return just the Customer object and have another method findWithRecordsById to return customer+records using @EntityGraph?

public interface CustomerRepository extends JpaRepository<Customer, UUID>{

    @EntityGraph(attributePaths = {"records"})
    Customer findWithRecordsById(UUID id);
...
}

Upvotes: 2

Related Questions