JPA替代Hibernate Projections.property

时间:2017-07-25 16:11:25

标签: java hibernate jpa

民间!

尝试限制从DB中提取的列数,并找到:Hibernate Criteria Query to get specific columns

Criteria cr = session.createCriteria(User.class)
    .setProjection(Projections.projectionList()
      .add(Projections.property("id"), "id")
      .add(Projections.property("Name"), "Name"))
    .setResultTransformer(Transformers.aliasToBean(User.class));

  List<User> list = cr.list();

当你使用Hibernate时这很棒,但是我试图用 JPA (JPA提供者 Hibernate tho)做同样的事情。 是否可以使用JPA进行操作? 我的意思是使用CriteriaBuilder限制列并映射到特定的对象?

另外,我看到了这个: https://docs.jboss.org/hibernate/orm/5.0/userguide/html_single/chapters/query/criteria/Criteria.html

Hibernate offers an older, legacy org.hibernate.Criteria API which should be considered deprecated. No feature development will target those APIs. Eventually, Hibernate-specific criteria features will be ported as extensions to the JPA javax.persistence.criteria.CriteriaQuery. For details on the org.hibernate.Criteria API, see Legacy Hibernate Criteria Queries.

似乎可以通过JPA的hibernate扩展来实现这一点吗?

1 个答案:

答案 0 :(得分:0)

JPA中没有替代语法,Hibernate是JPA的超集,它提供了JPA规范以外的功能。 在JPA中,您必须使用select语句(在您的情况下为multiselect语句)中单独显式进行投影。

标准查询

 // Create instance of CriteriaBuilder, where em is EntityManager
CriteriaBuilder cb = em.getCriteriaBuilder();      

  // Use CriteriaBuilder interface to create an instance 
  // of CriteriaQuery. For multiselect result set is Object [].
CriteriaQuery<Object[]> c = cb.createQuery(Object[].class);

   // Establish the root of the query by invoking from() to get back a Root object. 
Root<User> user = c.from(User.class); 

  // Establish the SELECT clause of the query by passing the root into the multiselect() method
criteriaQuery.multiselect(user.get("property1"), user.get("property2"));

替代方案是构造函数调用:

CriteriaQuery<User> c = cb.createQuery(User.class);
Root<User> user = c.from(User.class);
c.select(cb.construct(User.class,
                      user.get("property1"),
                      user.get("property2")));

TupleQuery

    CriteriaQuery<Tuple> c = cb.createTupleQuery();
    Root<User> user = c.from(User.class);
    c.select(cb.tuple(user.get("property1"), user.get("property2")));
    Query query = entityManager.createQuery(c);
    List<Tuple> results = query.getResultList();

还有array()方法(它还返回Object [])。

    c.select(cb.array(user.get("property1"), user.get("property2")));