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()方法明確的指定須要返回的字段名稱和類型信息。
相關文章
相關標籤/搜索