日期:2014-05-19  浏览次数:20585 次

很奇怪的问题org.hibernate.QueryException: Unable to resolve path
[code=XML][/code]今天搞了个测试用myeclipse下oracle8.1.7和hibernate3.0+spring2.0做个测试,平台是tomcate6.0

建了一个表叫test,里面有name,age等等几个属性吧
然后做映射
然后写dao查询
用了HibernateTemplate
然后就出现怪事了
如果用回调,使用createSQLQuery来运行sql语句,就没问题,一切查询正常

如果运行hql语句,比如"from po.test where test.name = sdf"
不管是直接用HibernateTemplate还是用回调,都会报下面这个错

org.hibernate.QueryException: Unable to resolve path [test.name], unexpected token [test] [SELECT * from po.test where test.name = sdf]


配置文件test.hbm.xml,把头部声明去掉了,
XML code

<hibernate-mapping>
    <class name="po.test" table="TEST" schema="TEST">
        <id name="id" type="java.lang.Long">
            <column name="ID" precision="22" scale="0" />
            <generator class="sequence" />
        </id>
        <property name="name" type="java.lang.String">
            <column name="NAME" length="12" />
        </property>
     ………………此处省略许多property配置
 </class>
<hibernate-mapping>





applicationContext.xml也省略了头尾,拷来一个SessionFactory和一个dao的设置部分
XML code

    <bean id="SessionFactory"
        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource">
            <ref bean="DataSource" />
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">
                    org.hibernate.dialect.Oracle8iDialect
                </prop>
            </props>
        </property>
        <property name="mappingResources">
            <list>
                <value>po/test.hbm.xml</value>
    
            </list>
        </property>
    </bean>
    <bean id="testDAO" class="dao.testDAO">
        <property name="sessionFactory">
            <ref bean="SessionFactory" />
        </property>
    </bean>




请问到底是什么问题呢?

------解决方案--------------------
就从你的这句HQL来分析原因吧:
"from po.test where test.name = sdf"

问题之一:
sdf是个字符串值,应该加单引号。不然Hibernate会把它作为类的属性看待,而你的类中是没有sdf这个属性的

问题之二:
from后直接写类名,不必加包名

问题之三:
test是类名,不能直接使用test.name(不能通过类来访问,就好像你不能通过类名去访问实例变量一样),请不要问为什么,记住这是HQL的语法要求就行了。
那怎么办呢?通常会用别名的方式解决,比如
from test as t where t.name = 'sdf'(别名就好像是test类的一个对象,通过对象就可以访问实例变量啦,哈哈)
所以你也可以这样写:
from test as test where test.name = 'sdf'(注意现在test.name中的test是别名了)

当然,仅对一个类进行操作,也可以不借助于别名:
from test where name = 'sdf'