问题
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));
}
回答1:
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);
...
}
来源:https://stackoverflow.com/questions/64013319/spring-data-jpa-hibernate-handling-associations