Hibernate JPQL:如何;选择新的Foo(null,null…someValue,…)?

Hibernate JPQL:如何;选择新的Foo(null,null…someValue,…)?,hibernate,jpa,jpql,Hibernate,Jpa,Jpql,例如,我有一个实体 public class Foo { private String col1; private String col2; private String col3; private String col4; //getters and setters } 我要做的是只选择col3和col4。但是我已经有了一个Foo构造函数,如下所示: public Foo (String col1, String col2) { this.col1

例如,我有一个实体

public class Foo {
   private String col1;
   private String col2;
   private String col3;
   private String col4;

   //getters and setters   
}
我要做的是
只选择
col3
col4
。但是我已经有了一个
Foo
构造函数,如下所示:

public Foo (String col1, String col2) {
   this.col1 = col1;
   this.col2 = col2;
}
因此,我不能为
col3
col4
使用另一个构造函数,因为它将具有相同的签名

到目前为止,我试图完成的是制作一个完整的构造函数,如:

public Foo (String col1, String col2, String col3, String col4) {
   this.col1 = col1;
   this.col2 = col2;
   this.col3 = col3;
   this.col4 = col4;
}
但是当我尝试在我的查询中执行以下操作时

SELECT new Foo(null, null, f.col3, f.col4)
FROM Foo f
我明白了

org.hibernate.hql.internal.ast.QuerySyntaxException:子树的意外结尾

虽然当我尝试

SELECT new Foo(f.col1, f.col2, f.col3, f.col4)
FROM Foo f
它按预期工作

编辑:

我试过了

Select f.col3, col4..
下面的错误被抛出

org.springframework.dao.InvalidDataAccessApiUsageException: Cannot create TypedQuery for query with more than one return using requested result type [com.lala.entity.Foo]; nested exception is java.lang.IllegalArgumentException: Cannot create TypedQuery for query with more than one return using requested result type [com.lala.entity.Foo]
你可以试试(但只是试试)

或者查看是否支持JPQL的cast()运算符(我不确定)
否则

Session Session=entityManager.unwrap(Session.class);
List List=session.createQuery(“从Foo f中选择f.col3、f.col4”).List()

这是特定于Hibernate的,您不需要为每个投影都使用特定的构造函数;只需创建一个空构造函数
Foo()
(至少受保护,我不记得是否允许private),然后让Hibernate从查询中将值注入
col3、col4
(如果基础数据库支持该函数,则支持
cast()
运算符)。

我知道这个问题很老,但您也可以这样做(如果演员阵容不适合你):

编辑:
JPA在将文本列映射到构造函数参数时忽略这些列,因此使用trim包装以让JPA知道文本值。

要选择单个列,请参阅此处-可能会有所帮助。如果是整数而不是字符串,您知道解决方案吗?
SELECT new Foo(cast(null as string), cast(null as string), f.col3, f.col4)
FROM Foo f
Session session = entityManager.unwrap(Session.class);
List<Foo> list = session.createQuery("select f.col3, f.col4 from Foo f").list()
String query = "select new Pojo( " +
        " trim(:null), " +
        " trim(:null), " +
        " f.col3, " +
        " f.col4 " +
        " ) " +
        " from Foo as f ";

return em.createQuery(query, Pojo.class)
        .setParameter("null", null)
        .getResultList();