Cast Hibernate result to a list of objects
hibernate, java
Solution
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
Problem
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.