Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast Hibernate result to a list of objects

Tags:

java

hibernate

I have a hibernate call in my DAO that looks like this

List<Associate> associate = (List<Associate>)session.createSQLQuery("SELECT * FROM associates WHERE fk_id = :id AND fk_associate_id = (SELECT id FROM users WHERE fk_user_type = 2)").setParameter("id", id).list();

I am getting an error saying that I cannot cast the resulting list to the model type Associate. I don't understand why this is happening. I am returning only the fields that are in the associates table.

like image 466
JohnnyQuestIsASellOut Avatar asked Feb 01 '11 14:02

JohnnyQuestIsASellOut


People also ask

What does query list() return in Hibernate?

list. Return the query results as a List. If the query contains multiple results pre row, the results are returned in an instance of Object[].

How to use list in Hibernate?

The <list> element will be used to define the rule for List collection used. The index of list is always of type integer and is mapped using the <list-index> element. The mapping document is an XML document having <hibernate-mapping> as the root element, which contains two <class>> elements corresponding to each class.

What is ResultTransformer in Hibernate?

The ResultTransformer is a very powerful mechanism, allowing you to customize a JPA or Hibernate query result set programmatically.

How do you map native query results to pojo?

Solution: JPA supports @SqlResultSetMappings which you can use to map the query result to a POJO. The following code snippet shows an example of such a mapping. The @ConstructorResult annotation defines a constructor call of the BookValue class.


1 Answers

You need to specify the class of entity the result should be converted to using addEntity(), because you are executing SQL query that doesn't know anything about entities:

List<Associate> associate = (List<Associate>) session.createSQLQuery(
    "SELECT * FROM associates WHERE fk_id = :id AND fk_associate_id = (SELECT id FROM users WHERE fk_user_type = 2)")
    .addEntity(Associate.class)
    .setParameter("id", id).list(); 

See also:

  • 18.1.2. Entity queries
like image 159
axtavt Avatar answered Sep 17 '22 17:09

axtavt