Hibernate经过SQLQuery接口执行原生态SQL查询

Execution of native SQL queries is controlled via the SQLQuery interface  java

Scalar queries--标量查询 sql

The most basic SQL query is to get a list of scalars (values). 数组

sess.createSQLQuery("SELECT * FROM CATS").list();
sess.createSQLQuery("SELECT ID, NAME, BIRTHDATE FROM CATS").list();

These will return a List of Object arrays (Object[]) with scalar values for each column in the CATS table. Hibernate will use ResultSetMetadata to deduce the actual order and types of the returned scalar values. app

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

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

This query specified: hibernate

  • the SQL query string scala

  • the columns and types to return code

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 underlyingresultset. 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. orm

It is possible to leave out the type information for all or some of the scalars. 对象

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

This is essentially the same query as before, but now ResultSetMetaData is used to determine the type of NAME and BIRTHDATE, where as the type of ID is explicitly specified.

How the java.sql.Types returned from ResultSetMetaData is mapped to Hibernate types is controlled by the Dialect. If a specific type is not mapped, or does not result in the expected type, it is possible to customize it via calls to registerHibernateType in the Dialect.



以上来自于hibernate-release-4.1.7.Final 的文档,经过这种方式会返回一系列对象数组,hibernate经过ResultSetMetaData(结果集的元数据),ResultSetMetaData接口能够得到关于查询数据的表名、字段名、字段类型等信息。为了不滥用ResultSetMetaData,hibernate能够经过使用addScalar()方法明确的指定须要返回的字段名称和类型信息。
相关文章
相关标签/搜索