使用本机SQL查询时如何指定数据类型? [英] How to specify data type when using native SQL query?

查看:427
本文介绍了使用本机SQL查询时如何指定数据类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用休眠模式.我已经编写了本机SQL查询,我想指定列之一的数据类型,如下所示.

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);

我要查询5列,而ID是其中的一列.但是,如果我使用addScalar,它不会返回所有列,而仅返回NAME.我将列类型指定为NAME列的原因是表中的CHAR(10),但是我想要的是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?

推荐答案

为避免使用ResultSetMetadata的开销,或者只是为了更明确地返回结果,可以使用addScalar():

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)

此查询指定:

the SQL query string

the columns and types to return

这将返回Object数组,但现在将不使用ResultSetMetadata,而是从基础结果集中分别显式获取ID,NAME和BIRTHDATE列,分别为Long,String和Short.这也意味着即使查询使用*,也只会返回这三列,并且返回的列可能多于列出的三列.

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.

参考: http://docs.jboss.org/hibernate /orm/3.3/reference/zh-CN/html/querysql.html#d0e13646

因此,在您的情况下,再添加4个addScalar()方法,其列名和数据类型.

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

这篇关于使用本机SQL查询时如何指定数据类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆