JPA &Criteria API - 仅选择特定列 [英] JPA & Criteria API - Select only specific columns

查看:30
本文介绍了JPA &Criteria API - 仅选择特定列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想选择特定的列(例如 SELECT a FROM b).我有一个通用的 DAO,我想出的是:

I would like to select only specific columns (ex. SELECT a FROM b). I have a generic DAO and what I came up with is:

public List<T> getAll(boolean idAndVersionOnly) {
    CriteriaBuilder builder = manager.getCriteriaBuilder();
    CriteriaQuery<T> criteria = builder.createQuery(entityClazz);
    Root<T> root = criteria.from(entityClazz);
    if (idAndVersionOnly) {
        criteria.select(root.get("ID").get("VERSION")); // HERE IS ERROR
    } else {
        criteria.select(root);
    }
    return manager.createQuery(criteria).getResultList();
}

错误是:CriteriaQuery类型中的方法select(Selection)不适用于参数 (Path).我应该如何改变它?我想获得一个类型 T 对象,它只有 IDVERSION 字段,所有其他字段都是 null.

And the error is: The method select(Selection<? extends T>) in the type CriteriaQuery<T> is not applicable for the arguments (Path<Object>). How should I change that? I want to get a type T object that has only ID and VERSION fields, and all others are null.

Type T 扩展了 AbstractEntity ,它有这两个字段.

Type T extends AbstractEntity which has those 2 fields.

entityClazzT.class.

推荐答案

获取特定列的 JPA 方法之一是请求 元组对象.

One of the JPA ways for getting only particular columns is to ask for a Tuple object.

在您的情况下,您需要编写如下内容:

In your case you would need to write something like this:

CriteriaQuery<Tuple> cq = builder.createTupleQuery();
// write the Root, Path elements as usual
Root<EntityClazz> root = cq.from(EntityClazz.class);
cq.multiselect(root.get(EntityClazz_.ID), root.get(EntityClazz_.VERSION));  //using metamodel
List<Tuple> tupleResult = em.createQuery(cq).getResultList();
for (Tuple t : tupleResult) {
    Long id = (Long) t.get(0);
    Long version = (Long) t.get(1);
}

如果您有一个表示结果的类,则可以使用另一种方法,例如您的情况中的 T.T 不需要是实体类.如果 T 有一个构造函数,如:

Another approach is possible if you have a class representing the result, like T in your case. T doesn't need to be an Entity class. If T has a constructor like:

public T(Long id, Long version)

然后你可以直接在你的 CriteriaQuery 构造函数中使用 T :

then you can use T directly in your CriteriaQuery constructor:

CriteriaQuery<T> cq = builder.createQuery(T.class);
// write the Root, Path elements as usual
Root<EntityClazz> root = cq.from(EntityClazz.class);
cq.multiselect(root.get(EntityClazz_.ID), root.get(EntityClazz_.VERSION));  //using metamodel
List<T> result = em.createQuery(cq).getResultList();

请参阅此链接以获取进一步参考.

See this link for further reference.

这篇关于JPA &amp;Criteria API - 仅选择特定列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆