spring-data-jpa 当需要返回列表对象时,是否可以使用Hibernate原生查询?

tkclm6bt  于 2022-11-10  发布在  Spring
关注(0)|答案(1)|浏览(146)

我有两个表(在本例中,Customer和Product)要在查询中返回json,其中包含一个列表字段(一对多关系)

public class Customer {
    @Id
    private Long id;

    private String name;

    @OneToMany(mappedBy = "customer", cascade = CascadeType.ALL)
    private List<Product> products;
}

Hibernate查询非常复杂,使用createNativeQuery()
对于返回单个Customer的Rest API,我只需运行第二个产品查询,并独立设置字段

customerDTO.setProduct(productsForCustomer);

但是现在我被要求构建一个API,该API返回给定特定条件的所有客户的列表-必须返回List<Customer>
使用nativeQuery是否可以实现这一点,或者我是否必须使用JQL重写实体的查询?

qyyhg6bp

qyyhg6bp1#

推荐的方法是JPQL。使用本机查询时,您必须通过处理结果集来填充实体。
我想这取决于您的复杂查询是否可以使用JPQL
最简单的形式就是

em.createQuery("select c from Customer c join fetch c.products where c.id = :id", Customer.class).setParameter("id", id).getResultList();

相关问题