【问题标题】:How JPA Criteria API worksJPA 标准 API 的工作原理
【发布时间】:2021-03-16 13:24:17
【问题描述】:

我是新手,我有一个关于 JPA 标准查询的任务。 我试图理解这段代码的确切含​​义。

EntityManager em = ...
CriteriaBuilder qb = em.getCriteriaBuilder();
CriteriaQuery<Person> c = qb.createQuery(Person.class);
Root<Person> p = c.from(Person.class);
Predicate condition = qb.gt(p.get(Person_.age), 20);
c.where(condition);
TypedQuery<Person> q = em.createQuery(c); 
List<Person> result = q.getResultList();

您能否详细解释每一行以及为什么要遵循这些步骤? 我在网上找到了很多资源,但我仍然无法获得完整的数字......

例如:createQuery(Person.class) 是什么意思?或者 TypedQuery 和 CriteriaQuery 之间的真正区别?

我从 Martin Fowler 的博客中阅读了查询对象的含义: “查询对象是一个解释器 [Gang of Four],即可以将自身形成 SQL 查询的对象结构。您可以通过引用类和字段而不是表和列来创建此查询。”

但是它的写法我还是不太明白...

谢谢

【问题讨论】:

    标签: hibernate jpa criteria-api criteriaquery


    【解决方案1】:
    @Entity
    public class Person {
        @Id
        Long id;
        String name;
        Integer age;
    
        //getters, setters, toString, hashcode, etc ...
    }
    

    任务:创建查询以获取超过给定年龄的人的姓名


    1. TypedQuery 允许您手动编写JPQL 查询。

    EntityManager em;
    
    public List<String> getNamesOfPersonsOlderThan(Integer minAge) {
        String jpql = "select p.name from Person p where p.age>:minAge";
        
        TypedQuery<String> query = em.createQuery(jpql, String.class);
    
        return query.setParameter("minAge", minAge).getResultList();
    }
    

    2.CriteriaQuery 提供了一种编程方式来定义与平台无关的动态类型安全查询

    EntityManager em;
    
    public List<String> getNamesOfPersonsOlderThan(Integer minAge) {
    
        //CriteriaBuilder is used to construct criteria queries, compound selections, expressions, predicates, orderings.
        CriteriaBuilder cb = em.getCriteriaBuilder();
    
        //Create a query returns String or List<String> as a result
        CriteriaQuery<String> query = cb.createQuery(String.class);
    
        //Create and add a query root corresponding to the given entity
        Root<Person> person = query.from(Person.class);
    
        //Create a predicate to select persons older than minAge
        Predicate condition = cb.gt(person.get(Person_.age), minAge);
    
        //Set the query selection and predicate
        query.select(person.get(Person_.name)).where(condition);
    
        //Pass the query to the entity manager and get the result
        return em.createQuery(query).getResultList();
    }
    

    查询大致如下from(Person).select(Person.name).where(Person.age &gt; minAge)

    【讨论】:

      猜你喜欢
      • 2012-06-28
      • 2017-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-06
      • 2011-05-04
      • 2018-08-22
      相关资源
      最近更新 更多