Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify data type when using native SQL query?

I am using hibernate. I have written native SQL query and I would like to specify data type of one of the column as below.

sqlQuery.addScalar("NAME", STRING);

I am querying 5 columns and ID is one of the column among them. But if I use addScalar, it is not returning all the columns and is returning only NAME. the reason why I am specifying the column type is NAME column is of CHAR(10) in table but I want String type. How can I specify the datatype and get all the columns?

like image 318
user1016403 Avatar asked Oct 12 '12 13:10

user1016403


1 Answers

To avoid the overhead of using ResultSetMetadata, or simply to be more explicit in what is returned, one can use addScalar():

sess.createSQLQuery("SELECT * FROM CATS")
 .addScalar("ID", Hibernate.LONG)
 .addScalar("NAME", Hibernate.STRING)
 .addScalar("BIRTHDATE", Hibernate.DATE)

This query specified:

the SQL query string

the columns and types to return

This will return Object arrays, but now it will not use ResultSetMetadata but will instead explicitly get the ID, NAME and BIRTHDATE column as respectively a Long, String and a Short from the underlying resultset. This also means that only these three columns will be returned, even though the query is using * and could return more than the three listed columns.

Ref: http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/querysql.html#d0e13646

So, in your case add 4 more addScalar() method, with its column name and Data type.

like image 102
Vinit Prajapati Avatar answered Oct 25 '22 12:10

Vinit Prajapati