在Hibernate Native SQL查询中使用占位符

时间:2012-01-05 15:35:34

标签: hibernate

我有一个实体书,它与发布者保持多对一的关系。这是Book

的hi​​bernate映射文件
<hibernate-mapping package="com.pramati.model">
    <class name="Book" table="BOOK">
        <id name="id" column="ID" type="long">
            <generator class="native"/>
        </id>
        <property name="name" column="NAME" type="string"/>
        <property name="isbn" type="int">
            <column name="ISBN" unique="true" not-null="true"/>
        </property>
        <property name="price" column="PRICE" type="double"/>
        <property name="bookIndex" column="BOOK_INDEX" type="int"/>
        <many-to-one name="publisher" class="Publisher" column="PUBLISHER_ID" cascade="save-update,delete"/>
    </class>
</hibernate-mapping>

以下是我使用的原生查询:

String sql = "SELECT {b.*}  FROM BOOK book LEFT OUTER JOIN PUBLISHER pub ON book.PUBLISHER_ID = pub.ID  WHERE book.price > 100 ";
Query query = session.createSQLQuery(sql).addEntity("b", Book.class);
List list = query.list();

执行此操作时,我收到以下异常:

20:39:49,438 DEBUG SQL:401 - SELECT b.ID as ID0_0_, b.NAME as NAME0_0_, b.ISBN as ISBN0_0_, b.PRICE as PRICE0_0_, b.BOOK_INDEX as BOOK5_0_0_, b.PUBLISHER_ID as PUBLISHER6_0_0_ FROM BOOK book LEFT OUTER JOIN PUBLISHER pub ON book.PUBLISHER_ID = pub.ID WHERE book.price > 100 
20:39:49,466  WARN JDBCExceptionReporter:77 - SQL Error: 1054, SQLState: 42S22
20:39:49,467 ERROR JDBCExceptionReporter:78 - Unknown column 'b.ID' in 'field list'
Exception in thread "main" org.hibernate.exception.SQLGrammarException: could not execute query
    at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:67)
    at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
    at org.hibernate.loader.Loader.doList(Loader.java:2223)
    at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2104)
    at org.hibernate.loader.Loader.list(Loader.java:2099)
    at org.hibernate.loader.custom.CustomLoader.list(CustomLoader.java:289)
    at org.hibernate.impl.SessionImpl.listCustomQuery(SessionImpl.java:1695)
    at org.hibernate.impl.AbstractSessionImpl.list(AbstractSessionImpl.java:142)
    at org.hibernate.impl.SQLQueryImpl.list(SQLQueryImpl.java:152)
    at com.pramati.model.Publisher.main(Publisher.java:95)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'b.ID' in 'field list'
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)

为什么会这样?如果我只是在addEntity中将别名替换为'book'并尝试使用'select {book。*} ..'(即在SQL和addEntity方法中使用相同的别名)来获取它,它工作正常。

1 个答案:

答案 0 :(得分:2)

您应该使用{book.*}。否则SQL驱动程序不知道它引用的查询中的内容。

如果你看看引起的,你会发现它是抛出异常的mysql驱动程序。 Hibernate正在用{b.*}替换b.ID, ...,但驱动程序不知道字段映射到FROM子句中的内容。