2013-08-27 25 views
4

比如我有一個實體JPQL:如何「選擇新的Foo(NULL,NULL ... someValue中,..)

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

    //getters and setters 
} 

我想要做的是select只有col3col4。但是我已經有一個Foo構造象下面這樣:

public Foo (String col1, String col2) { 
    this.col1 = col1; 
    this.col2 = col2; 
} 

因此,我不能再有一個構造函數col3col4,因爲這將具有相同的簽名

我試圖到目前爲止完成是使完整構造,如:

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: unexpected end of subtree

雖然當我嘗試

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] 
+0

要選擇單個列,可以參考這裏 - http://stackoverflow.com/a/4536802/366964可能會有所幫助。 –

回答

4

您可以嘗試(但只是一種嘗試)錯誤

SELECT new Foo(cast(null as string), cast(null as string), f.col3, f.col4) 
FROM Foo f 

或尋找有關CAST()操作符JPQL如果支持(我不知道)
其他

Session session = entityManager.unwrap(Session.class); 
List<Foo> list = session.createQuery("select f.col3, f.col4 from Foo f").list() 

這是Hibernate的具體,你並不需要爲每一個具體的預測構造;只需創建一個空構造函數Foo()(至少受保護,我不記得是否允許私有)並讓Hibernate從您的查詢中將值注入col3, col4(如果您的基礎數據庫支持該函數,則支持cast()運算符)。

+0

我試過這個先生,但是出現了一個錯誤(請參閱編輯) – Incognito

1

我知道這個問題是舊的,但你也可以做(如果投不爲你工作):

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

編輯: JPA將它們映射到構造函數的參數時,忽略了文字列,所以包裹修剪讓JPA意識到字面值。