Spring Data JPA/Hibernate handling associations

二次信任 提交于 2021-02-05 11:38:23

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!