本文介绍了Spring Data JPA/休眠处理关联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要基于参数检索或不从实体获得某些关联.在下面的示例中,仅当参数通过我的api传递时,我才需要获取记录列表.您能推荐一种使用休眠/弹簧数据实现此目的的方法吗?我正在寻找最干净,类似Spring数据的方法.

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

我的存储库为空:

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

推荐答案

如何使用基本的 findById 仅返回Customer对象,并使用另一种方法 findWithRecordsById 返回客户+使用 @EntityGraph 记录吗?

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

这篇关于Spring Data JPA/休眠处理关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 00:09