jpa多表关联动态查询
时间: 2023-07-13 12:33:37 浏览: 41
在 JPA 中,多表关联动态查询可以通过 Criteria API 或者 JPQL 来实现。
下面是一个使用 Criteria API 的示例:
```java
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<Order> query = cb.createQuery(Order.class);
Root<Order> order = query.from(Order.class);
Join<Order, Customer> customer = order.join("customer");
Predicate predicate = cb.equal(customer.get("name"), "John");
query.select(order).where(predicate);
List<Order> orders = entityManager.createQuery(query).getResultList();
```
上面的代码中,我们创建了一个 CriteriaBuilder 对象,用于构建查询条件。然后创建了一个 CriteriaQuery 对象,指定查询的实体类为 Order.class。接着使用 Root 对象引用 Order 实体,使用 Join 对象引用 Customer 实体,并通过 join 方法指定 Order 和 Customer 的关联关系。然后创建了一个 Predicate 对象,用于指定查询条件,这里我们查询 Customer 的名称为 John 的所有订单。最后通过 createQuery 方法执行查询,并通过 getResultList 方法获取查询结果。
如果你更喜欢使用 JPQL,可以使用类似如下的语句:
```sql
SELECT o FROM Order o JOIN o.customer c WHERE c.name = 'John'
```
上面的语句中,我们使用 JOIN 关键字指定了 Order 和 Customer 的关联关系,并通过 WHERE 子句指定了查询条件。最后通过执行该语句来获取查询结果。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)