Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

New object with HQL

Trying to create an object from an HQL query, but just can't figure out what i'm doing wrong.

Query:

String query = "SELECT product.code, SUM(product.price), COUNT(product.code) from Product AS product GROUP BY product.code" 

(or should I use new MyCustomList(product.code, SUM(... , even though it's not mapped?) Now I want to cast this returned list into a similar object:

class MyCustomList{   public String code;   public BigDecimal price;   public int total;    // Constructor   public MyCustomList(String code, String price, int total){ //... 

Retrieving the data:

// This throws ClassCastException     List<MyCustomList> list = MyClass.find(query).fetch(); 

Using Play framework

like image 399
Indrek Avatar asked Oct 26 '10 20:10

Indrek


People also ask

What is the difference between JPQL and Hql?

The Hibernate Query Language (HQL) and Java Persistence Query Language (JPQL) are both object model focused query languages similar in nature to SQL. JPQL is a heavily-inspired-by subset of HQL. A JPQL query is always a valid HQL query, the reverse is not true however.

How can I get result set in hibernate?

Hibernate ResultSet traversing optionsgetResultList() method call. Hibernate also supports scrollable ResultSet cursors through its specific Query. scroll() API. The only apparent advantage of scrollable ResultSets is that we can avoid memory issues on the client-side, since data is being fetched on demand.


2 Answers

I think that the section 15.6. The select clause covers what you're trying to achieve:

15.6. The select clause

...

Queries can return multiple objects and/or properties as an array of type Object[]:

select mother, offspr, mate.name from DomesticCat as mother     inner join mother.mate as mate     left outer join mother.kittens as offspr 

Or as a 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 

Or - assuming that the class Family has an appropriate constructor - as an actual typesafe Java object:

select new Family(mother, mate, offspr) from DomesticCat as mother     join mother.mate as mate     left join mother.kittens as offspr 

In your case, you probably want:

SELECT new MyCustomList(product.code, SUM(product.price), COUNT(product.code)) from Product AS product GROUP BY product.code 

Where MyCustomList is not necessarily a mapped entity.

like image 140
Pascal Thivent Avatar answered Oct 10 '22 17:10

Pascal Thivent


I know that this is an old post, but you can also use for HQL:

Query query = session.createQuery("SELECT code AS code FROM Product");  

or this for SQL:

Query query = session.createSQLQuery("SELECT code AS code FROM Product"); 

with:

query.setResultTransformer(Transformers.aliasToBean(MyCustomList.class)); 
like image 35
Jason Glez Avatar answered Oct 10 '22 16:10

Jason Glez