【问题标题】:Alternate way for the code using JPA criteria使用 JPA 标准的代码的替代方式
【发布时间】:2020-05-02 03:53:00
【问题描述】:

随着 Hibernate 5.2.2 中 Criteria 类中的 createCriteria() 的弃用,它的许多相关函数无法再使用。我找到了 criteria.createAlias(String, String) 的替代用途,并从以下链接添加了 Restriction Deprecated createCriteria method in Hibernate 5 但我找不到如何在 JPA 标准中替换标准中可用的以下功能:

    criteria.setProjection(Projections.projectionList()
                           .add(Projections.distinct(Projections.property("student.id")), "id")
                           .add(Projections.property("student.name"), "name"));
    criteria.addOrder(Order.asc("student.name"));
    if (limit != null)
        criteria.setMaxResults(limit);
    if (offset != null)
        criteria.setFirstResult(offset);
    criteria.setResultTransformer(new AliasToBeanResultTransformer(Student.class));

请提供另一种使用 JPA 标准 API 编写相同代码的方法。

【问题讨论】:

    标签: hibernate hibernate-criteria jpa-criteria


    【解决方案1】:

    到目前为止,我找到了以下替代方式:

        CriteriaBuilder builder = sessionFactory.getCriteriaBuilder();
        CriteriaQuery<Student> criteriaQuery = builder.createQuery(Student.class);
        //Perform the required join
    criteriaQuery.multiselect(student.get("id").alias("id"),student.get("name").alias("name")).distinct(true);
        criteriaQuery.orderBy(builder.asc(student.get("name")));
        TypedQuery typedQuery = entityManager.createQuery(criteriaQuery);
        if (limit != null)
          typedQuery.setMaxResults(limit);
        if (offset != null)
          typedQuery.setFirstResult(offset);
        List<Student> resultList = typedQuery.getResultList();
    

    上述解决方案解决了我的问题。 JPA 标准不需要AliasToBeanResultTransformer()。它将自己转换为所需的 bean。

    【讨论】:

      猜你喜欢
      • 2010-12-12
      • 1970-01-01
      • 2017-06-21
      • 1970-01-01
      • 1970-01-01
      • 2011-03-13
      • 2012-07-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多