Nuovo oggetto con HQL
-
26-09-2019 - |
Domanda
Il tentativo di creare un oggetto da una query HQL, ma proprio non riesco a capire quello che sto facendo male.
Domanda:
String query = "SELECT product.code, SUM(product.price), COUNT(product.code)
from Product AS product
GROUP BY product.code"
(o dovrei utilizzare le nuove MyCustomList (product.code, SUM (..., anche se non è mappato?) Ora voglio lanciare questa lista restituita in un oggetto simile:
class MyCustomList{
public String code;
public BigDecimal price;
public int total;
// Constructor
public MyCustomList(String code, String price, int total){ //...
il recupero dei dati:
// This throws ClassCastException
List<MyCustomList> list = MyClass.find(query).fetch();
Utilizzando quadro Riproduzione
Soluzione
Credo che la sezione href="http://docs.jboss.org/hibernate/core/3.5/reference/en/html/queryhql.html#queryhql-select" 15,6 . coperture clausola select ciò che si sta cercando di raggiungere:
15,6. La clausola select
...
Le query può restituire più oggetti e / o proprietà come un array di tipo
Object[]
:select mother, offspr, mate.name from DomesticCat as mother inner join mother.mate as mate left outer join mother.kittens as offspr
O come un
List
:select new list(mother, offspr, mate.name) from DomesticCat as mother inner join mother.mate as mate left outer join mother.kittens as offspr
O - supponendo che il
Family
di classe ha un costruttore appropriato - come attuale typesafe oggetto Java:select new Family(mother, mate, offspr) from DomesticCat as mother join mother.mate as mate left join mother.kittens as offspr
Nel tuo caso, probabilmente si desidera:
SELECT new MyCustomList(product.code, SUM(product.price), COUNT(product.code))
from Product AS product
GROUP BY product.code
Dove MyCustomList
non è necessariamente un'entità mappata.
Altri suggerimenti
So che questo è un vecchio post, ma si può anche utilizzare per HQL:
Query query = session.createQuery("SELECT code AS code FROM Product");
o questo per SQL:
Query query = session.createSQLQuery("SELECT code AS code FROM Product");
con:
query.setResultTransformer(Transformers.aliasToBean(MyCustomList.class));