JayPea JayPea - 9 months ago 51
SQL Question

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

Answer Source

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