hibernate3.2多表關聯查詢常見問題

1.org.hibernate.hql.ast.QuerySyntaxException: user is not mapped [from user]錯誤java

今天學習hibernate。用MyEclipse部署。可是出現
org.hibernate.hql.ast.QuerySyntaxException: user is not mapped [from user]
在網上查了緣由:
一、
hibernate.cfg.xml少了不少映射.爲何會少呢?由於個人都是拷貝過來的。不是自動生成的。另外 hibernate.cfg.xml,要放在根目錄下。數據庫

把你要映射的都寫上去。
<mapping resource="....包名.../Companyinfo.hbm.xml" />
<mapping resource="....包名.../Companyinfo.hbm.xml" />
<mapping resource="....包名.../Companyinfo.hbm.xml" />
<mapping resource="....包名.../Companyinfo.hbm.xml" />
<mapping resource="....包名.../Companyinfo.hbm.xml" />app

二、現象:
使用hql="from person" 出現" person is not mapped " 錯誤

配置文件以下:
<hibernate-mapping>
<class name="src.Person"
table="person">
<id name="name"/>

<property name="password"/>
</class>
</hibernate-mapping>
原 因:
hql是寫的是PO對象,不是table名

故改成配置文件中的紅色部分的類名便可。學習

 

我出現的是第二種狀況,記錄一下。fetch

2.spa

org.hibernate.QueryException: could not resolve propertyhibernate

 

通常地,若是涉及到屬性類型沒法解析的異常,可能出現問題的地方有:xml

數據庫字段與持久化類映射文件,以及持久化類文件中屬性名稱或者類型可能不相匹配;對象

持久化類映射文件中屬性類型可能有問題,好比,若是使用Java類型,注意大寫(如type="java.lang.String"),若是使用Hibernate類型,使用小寫(如type="string")。ip

 

3.illegal attempt to dereference collection

from Department as d where d.employees.name='Tom';

運行時出現異常:org.hibernate.QueryException: illegal attempt to dereference collection

是由於:在上面的HQL語句中,Department的關聯實體employees是一個集合,而不直接是一個Employee實體。

在Hibernate3.2.2之前的版本,Hibernate會對關聯實體自動使用隱式的inner join,

也就是說以下SQL語句不會有任何問題 :from Department as d where d.employees.name='Tom';

從Hibernate3.2.3之後,Hibernate改變了這種隱式的inner join的策略

對於以下這條語句:

from Department as d where d.employees.name='Tom';

若是employees是普通組件屬性,或單個的關聯實體,則Hibernate會自動生成隱式的inner join

若是myEvents是也一個集合,那麼對不起!系統將會出現 org.hibernate.QueryException: illegal attempt to dereference collection異常。
據Hibernate官方說法: 
這樣可讓這使得隱含關聯更具肯定性(原文:This makes implicit joins more deterministic )。

推薦這樣寫:

from Department as d inner join fetch d.employees e where e.name='Tom';

相關文章
相關標籤/搜索