【发布时间】: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