What does addScalar do?

前端 未结 4 958
忘了有多久
忘了有多久 2020-12-14 06:37

The JavaDoc says:

SQLQuery org.hibernate.SQLQuery.addScalar(String columnAlias, Type type)

Declare a scalar query result

I know what

4条回答
  •  再見小時候
    2020-12-14 07:32

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

    session.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.

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

    session.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.

    copied from this.

提交回复
热议问题