简体   繁体   中英

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));
}

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);
...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM