[英]Hibernate JPA Meta Model -- reference nested properties?
Suppose an entity model where an Employee
has a Supervisor
who has an id
.假设一个实体模型,其中Employee
有一个id
的Supervisor
。 Using hibernate-jpamodelgen
to generate the meta model for the entities, how can I query a nested field?使用hibernate-jpamodelgen
为实体生成元模型,如何查询嵌套字段?
For instance, "get all employees whose supervisor has id 4", using JpaSpecificationExecutor
:例如,“使用JpaSpecificationExecutor
获取主管 ID 为 4 的所有员工”:
Page<Employee> getEmployeesBySupervisorId(int id) {
return findAll((root, query, criteriaBuilder) -> {
return criteriaBuilder.equal(root.get(Employee_.supervisor.id), id);
});
}
Note that Employee_
is the model meta class for Employee
(and was generated by Hibernate).需要注意的是Employee_
是模型元类Employee
(和由Hibernate生成)。
This code will produce an error because the id
symbol cannot be found on type SingularAttribute<Employee, Supervisor>
.此代码将产生错误,因为在SingularAttribute<Employee, Supervisor>
类型上找不到id
符号。 I get that, but it seems like these should somehow be chainable.我明白了,但似乎这些应该以某种方式可以链接。 I can't find great examples of how to do this cleanly.我找不到如何干净地做到这一点的好例子。
In order to navigate to related entities, you must use From#join()
join method, which works well with MetaModel:为了导航到相关实体,您必须使用From#join()
join 方法,该方法与 MetaModel 配合良好:
CriteriaQuery<Employee> cq = criteriaBuilder.createQuery(Employee.class);
Root<Employee> from = cq.from(Employee.class);
Predicate p = criteriaBuilder.equal(from.join(Employee_.supervisor).get(Supervisor_.id), id);
See also也可以看看
Oracle's Java EE Tutorial - Using the Criteria API and Metamodel API to Create Basic Typesafe Queries Oracle 的 Java EE 教程 - 使用 Criteria API 和元模型 API 创建基本类型安全查询
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.