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.
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[].
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.
The ResultTransformer is a very powerful mechanism, allowing you to customize a JPA or Hibernate query result set programmatically.
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.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With