Son*_*yen 5 java json criteria-api hibernate-criteria criteriaquery
我有 2 张桌子
| ID | 姓名 |
|---|---|
| 1 | 亚历克斯 |
| ID | 姓名 | 地位 | 企业ID |
|---|---|---|---|
| 7 | 苹果12 | 积极的 | 1 |
| 8 | 苹果11 | 积极的 | 1 |
| 6 | iphone13 | 禁用 | 1 |
这种关系是一对多的(一个企业有多个产品)。我想和Enterprise他们所有人Product一起得到一个条件是Status这样Product的ACTIVE
我怎样才能得到json的结果是
{
"id": "1",
"name": "Alex",
"products": [
{
"id": "7",
"name": "Iphone12",
},
{
"id": "8",
"name": "Iphone11",
}
]
}
Run Code Online (Sandbox Code Playgroud)
假设您的实体模型是:
@Entity
class Enterprise {
...
@OneToMany
List<Product> products;
}
@Entity
class Product {
...
String status;
}
Run Code Online (Sandbox Code Playgroud)
以下标准应该有效:
CriteriaQuery<Enterprise> criteria = builder.createQuery(Enterprise.class);
Root<Author> root = criteria.from( Enterprise.class );
Join<Object, Object> productsJoin = root.join( "products" );
criteria.where( builder.equal( productsJoin.get("status"), "ACTIVE" ) );
List<Enterprise> result = session.createCriteria(criteria).getResultList();
Run Code Online (Sandbox Code Playgroud)
与 HQL 查询相同:
from Enterprise e join e.products p
where p.status = 'ACTIVE'
Run Code Online (Sandbox Code Playgroud)
如果您想立即加载关联,可以替换root.join为root.fetch:
CriteriaQuery<Enterprise> criteria = builder.createQuery(Enterprise.class);
Root<Author> root = criteria.from( Enterprise.class );
Join<Object, Object> productsJoin = (Join<Object, Object>)root.fetch( "products" );
criteria.where( builder.equal( productsJoin.get("status"), "ACTIVE" ) );
List<Enterprise> result = session.createCriteria(criteria).getResultList();
Run Code Online (Sandbox Code Playgroud)
这是等效的 HQL 查询:
from Enterprise e join fetch e.products p
where p.status = 'ACTIVE'
Run Code Online (Sandbox Code Playgroud)
您可以在本文或Hibernate ORM 文档中找到更多示例。
| 归档时间: |
|
| 查看次数: |
6551 次 |
| 最近记录: |