【问题标题】:Spring Data JPA/Hibernate handling associationsSpring Data JPA/Hibernate 处理关联
【发布时间】:2021-01-08 18:58:55
【问题描述】:

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

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> {

}

在我的服务中,我正在做类似的事情:

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

但我想做的是:

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

【问题讨论】:

  • 作为旁注,为什么你的Record 类中同时有UUID customerId;Customer customer;
  • 我只使用 UUID 进行查询。因为如果我需要进行查询,我需要有一个客户实例,对吧?

标签: java spring hibernate spring-data-jpa


【解决方案1】:

如何使用基础findById 仅返回客户对象并使用另一个方法findWithRecordsById 使用@EntityGraph 返回客户+记录?

public interface CustomerRepository extends JpaRepository<Customer, UUID>{

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

【讨论】:

  • 感谢您的推荐。我不知道这个@EntityGraph。我去看看。
  • 我不确定我是否理解正确。当我调用默认的 findById 时,它还会返回关联的记录。
  • 它是否在相同/单个查询中返回?
  • 我可以看到调用基本 findById 产生的两行休眠日志: Hibernate: select customer0_.id as id1_1_0_,...... from CUSTOMER customer0_ where customer0_.id=? Hibernate: select records0_.customer_id as customer5_2_0_,..... from RECORD records0_ where records0_.customer_id=?
  • 好的,抱歉,我理解了这个问题。我正在使用 lombok @Data 它生成一个 toString 方法打印记录,并且在我没有注意到的情况下调用它。好的,谢谢,我会看看 EntityGraph 部分
猜你喜欢
  • 1970-01-01
  • 2017-07-17
  • 2019-07-20
  • 2016-06-26
  • 2016-10-15
  • 1970-01-01
  • 2017-02-24
  • 1970-01-01
  • 2021-05-22
相关资源
最近更新 更多