Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using sql column names in hibernate createSQlquery result

Tags:

I have a couple of sql views with composite primary keys that I want to query, and since Hibernate makes it a pain to work with composite keyes, I'm using createSQLQuery. The problem is that this method can only return a List, and I need to refer to the colums by their index.

Any chance I could do something like jdbc and refer to the columns by their sql name instead of their index?

like image 323
Ricardo Avatar asked Apr 09 '10 06:04

Ricardo


People also ask

How can I get result set in hibernate?

Hibernate ResultSet traversing optionsgetResultList() method call. Hibernate also supports scrollable ResultSet cursors through its specific Query. scroll() API. The only apparent advantage of scrollable ResultSets is that we can avoid memory issues on the client-side, since data is being fetched on demand.

Can we write SQL query in hibernate?

You can use native SQL to express database queries if you want to utilize database-specific features such as query hints or the CONNECT keyword in Oracle. Hibernate 3. x allows you to specify handwritten SQL, including stored procedures, for all create, update, delete, and load operations.

What is in Hibernate query?

Hibernate Query Language (HQL) is an object-oriented query language, similar to SQL, but instead of operating on tables and columns, HQL works with persistent objects and their properties. HQL queries are translated by Hibernate into conventional SQL queries, which in turns perform action on database.


1 Answers

Query query=session.createSQLQuery("your query"); query.setResultTransformer(AliasToEntityMapResultTransformer.INSTANCE); List<Map<String,Object>> aliasToValueMapList=query.list(); 

As you can figure out from code, the list contains Map objects representing each row. Each Map object will have column name as key and value as value.

Note: This work for SQLQuery, if your using AliasToEntityMapResultTransformer on hql query without specifying aliases you will get index value as key.

If you are again transforming aliasToValueMapList to your POJO list, I advice you to create your own ResultTransformer and return your custom object from 'transformTuple' method.

like image 61
Adisesha Avatar answered Oct 05 '22 00:10

Adisesha