Inc*_*ito 8 hibernate jpa jpql
例如,我有一个实体
public class Foo {
private String col1;
private String col2;
private String col3;
private String col4;
//getters and setters
}
Run Code Online (Sandbox Code Playgroud)
我想做的select只是col3和col4.但是我已经有了Foo如下构造函数:
public Foo (String col1, String col2) {
this.col1 = col1;
this.col2 = col2;
}
Run Code Online (Sandbox Code Playgroud)
因此,我不能拥有另一个构造函数col3,col4因为它将具有相同的签名.
到目前为止我要完成的是制作一个完整的构造函数,如:
public Foo (String col1, String col2, String col3, String col4) {
this.col1 = col1;
this.col2 = col2;
this.col3 = col3;
this.col4 = col4;
}
Run Code Online (Sandbox Code Playgroud)
但是当我尝试在我的查询中执行类似下面的操作时
SELECT new Foo(null, null, f.col3, f.col4)
FROM Foo f
Run Code Online (Sandbox Code Playgroud)
我明白了
org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected end of subtree
虽然当我尝试
SELECT new Foo(f.col1, f.col2, f.col3, f.col4)
FROM Foo f
Run Code Online (Sandbox Code Playgroud)
它按预期工作.
编辑:
我试过了
Select f.col3, col4..
Run Code Online (Sandbox Code Playgroud)
并抛出以下错误
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]
Run Code Online (Sandbox Code Playgroud)
你可以尝试(但只是一试)
SELECT new Foo(cast(null as string), cast(null as string), f.col3, f.col4)
FROM Foo f
Run Code Online (Sandbox Code Playgroud)
或找有关CAST()操作符JPQL如果支持(我不知道)
其他
Session session = entityManager.unwrap(Session.class);
List<Foo> list = session.createQuery("select f.col3, f.col4 from Foo f").list()
Run Code Online (Sandbox Code Playgroud)
这是特定于Hibernate的,并且您不需要为每个投影都使用特定的构造函数; 只需创建一个空构造函数Foo()(至少受保护,我不记得是否允许私有)并让Hibernate col3, col4从查询中注入值(cast()如果底层数据库支持该函数,则支持运算符).
| 归档时间: |
|
| 查看次数: |
4400 次 |
| 最近记录: |