[英]Criteria Api Vs QueryDsl Vs JPA metamodel
I am a bit confused about these three concepts.我对这三个概念有点困惑。
From what I have read, One of the major benifits of using QueryDsl or JPA metamodel is type safety.根据我的阅读,使用 QueryDsl 或 JPA 元模型的主要好处之一是类型安全。
But I can achieve type safety even with Criteria API's.但即使使用 Criteria API,我也可以实现类型安全。 (I am using JPA with eclipselink)
(我在 eclipselink 中使用 JPA)
javax.persistence.EntityManager
has two variants javax.persistence.EntityManager
有两个变体
public Query createQuery(String sqlString);
public <T> TypedQuery<T> createQuery(CriteriaQuery<T> criteriaQuery);
I agree with first version where I pass sql as string I don't get type safety.我同意第一个版本,我将 sql 作为字符串传递我没有类型安全。 But with the second version I get type safety.
但是在第二个版本中,我获得了类型安全。 Or am I missing something here?
还是我在这里遗漏了什么? Can someone explain with an example how using criteria is not type safe.
有人可以用一个例子来解释如何使用标准不是类型安全的。
What is the difference between QueryDsl and JPA static meta model ? QueryDsl 和 JPA 静态元模型有什么区别?
The syntax you provided is JPQL not a Criteria Api.您提供的语法是JPQL而不是 Criteria Api。 JPQL has query types @Query, @TypedQuery, @NamedQuery and they are written in plain JPQL which is error prone.
JPQL 有查询类型@Query、@TypedQuery、@NamedQuery,它们是用简单的 JPQL 编写的,很容易出错。 We have also @NativeQuery which should be avoided if possible.
我们还有@NativeQuery,如果可能的话应该避免。
There is other more safe options like Criteria Api or QueryDSL for querying only.还有其他更安全的选项,如 Criteria Api 或 QueryDSL 仅用于查询。
Criteria Api can be used with string based attributes Criteria Api可以与基于字符串的属性一起使用
CriteriaQuery<Employee> query = cb.createQuery(Employee.class);
Root<Employee> employee = query.from(Employee.class);
query.select(employee)
.where(cb.equal(employee.get("dept"), "Admin"));
Or we can reference attributes using metamodel class generated by Jpa metamodel或者我们可以使用Jpa 元模型生成的元模型类来引用属性
Root<Employee> employee = query.from(Employee.class);
query.select(employee)
.where(cb.equal(employee.get(Employee_.dept), "Admin"));
And there is QueryDSL which is more intuitive(IMHO) alternative to Criteria API.还有QueryDSL ,它比 Criteria API 更直观(恕我直言)。
QEmployee employee = QEmployee.employee;
query.from(employee).where(employee.dept.eq("Admin"))
您可以在 Criteria API 中使用 JPA 元模型来确保类型安全,但与 QueryDSL 相比,criteria api 相当复杂
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.