gpt4 book ai didi

java - Hibernate Projections.property 的 JPA 替代方案

转载 作者:行者123 更新时间:2023-12-01 20:07:42 34 4
gpt4 key购买 nike

各位!

尝试限制从数据库获取的列数并发现: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)。 是否可以使用 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 扩展来做到这一点?

最佳答案

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")));

元组查询

    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")));

关于java - Hibernate Projections.property 的 JPA 替代方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45308559/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com