JayPea
JayPea

Reputation: 9691

Hibernate: Is there a way to automatically convert native SQL results to a custom object?

I have a native SQL query that returns several computed results (such as sums and averages from several tables) and I want to load these results into a custom object that contains all the necessary fields. I'm aware that Hibernate provides the addEntity method, which allows you to specify the type of mapped entity that your results represent.

In this case, since the results are taken from several tables, the custom object that I'm using is not a mapped entity. Is there a way to make hibernate return a List<CustomObject> or will I have to manually copy the results to the proper objects? Thanks.

Query query = this.sessionFactory.getCurrentSession().createSQLQuery(queryString.toString());

return (List<CustomObject>)query.list(); //doesn't work, obviously

Upvotes: 3

Views: 10225

Answers (1)

mindas
mindas

Reputation: 26703

Look at result transformers. They are designed to do exactly what you are looking for and work for both HQL and SQL.

Upvotes: 5

Related Questions