简体   繁体   中英

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?

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.

This is working as it is supposed to work. Either it can use ResultSetMetaData and return you all the values returned from the query or it can use provided type inputs and return the columns provided with the types.

If there is no problem, add the type for remaining FOUR columns as well.

     sqlQuery.addScalar("NAME", STRING).
     .addScalar("ID", Hibernate.LONG)
     .addScalar("COLUMN3", STRING)
     .addScalar("COLUMN4", STRING)
     .addScalar("COLUMN5", STRING);

Update the column names and data type as per your actual column names and their data types.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM