[英]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.
我已经编写了本机SQL查询,我想指定列之一的数据类型,如下所示。
sqlQuery.addScalar("NAME", STRING);
I am querying 5 columns and ID
is one of the column among them. 我正在查询5列,
ID
是其中的一列。 But if I use addScalar
, it is not returning all the columns and is returning only NAME
. 但是,如果我使用
addScalar
,它不会返回所有列,而仅返回NAME
。 the reason why I am specifying the column type is NAME
column is of CHAR(10)
in table but I want String
type. 我将列类型指定为
NAME
列的原因是表中的CHAR(10)
,但我想要String
类型。 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(): 为了避免使用ResultSetMetadata的开销,或者只是为了更明确地说明返回的内容,可以使用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. 这将返回Object数组,但是现在将不使用ResultSetMetadata,而是从基础结果集中显式获取ID,NAME和BIRTHDATE列,分别为Long,String和Short。 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 参考: 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. 因此,在您的情况下,再添加4个
addScalar()
方法及其列名和数据类型。
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. 它可以使用
ResultSetMetaData
并返回您从查询返回的所有值,也可以使用提供的类型输入并返回这些类型提供的列。
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. 根据实际的列名称及其数据类型更新列名称和数据类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.