2012-06-16 92 views
2

晚上好!休眠HQL映射異常列名

我一直在學習和部分使用hibernate一段時間,並且遇到了使用hql連接的麻煩。

我跟着這些指令只爲實踐,看看它甚至還可以...
http://www.java2s.com/Tutorial/Java/0350__Hibernate/HSQLJoinTwoClasses.htm

他基本上產生3類: 供應商,產品,軟件
一個供應商有很多產品 許多產品一個供應商

一切工作得很好...除了我不能理解一個特定的事情,阻止我實現到我自己的代碼。 這是我無法理解的部分:

<class name="Product"> 

    <id name="id" type="int"> 
     <generator class="increment"/> 
    </id> 

    <property name="name" type="string"/> 
    <property name="description" type="string"/> 
    <property name="price" type="double"/> 

    <many-to-one name="supplier" class="Supplier" column="supplierId"/> 
</class> 


<class name="Supplier" > 
    <id name="id" type="int"> 
    <generator class="increment"/> 
    </id> 

    <property name="name" type="string"/> 
    <bag name="products" inverse="true" cascade="all,delete-orphan"> 
    <key column="supplierId"/> 
    <one-to-many class="Product"/> 
    </bag> 

</class> 

The query would be: 
SELECT s.name, p.name, p.price 
    FROM Product p INNER JOIN p.supplier AS s"; 

他爲什麼使用「供應商ID」爲列的值時,有沒有到處定義供應商ID。我無法弄清楚在後臺發生了什麼,或者爲什麼它在工作...

我一直在尋找一個年齡的解釋..希望你們中的一些人做了一些這樣的經驗,可以幫助我。會很棒。希望我不太模糊。

有一個愉快的一天, 邁克爾Kargl


解決方案

問題是,我錯過了在數據庫中的實際外鍵列名爲供應商ID ...

create table Product(
     id int, 
     name varchar, 
     description varchar, 
     price decimal(6,2), 
     >>>> supplierid int <<<<< 
) 

(我永遠不會複製和粘貼這樣的代碼再次..)
其餘大部分由@carbontax's post@MikkoMaunu's post

回答

2

你說supplierId沒有定義,但它是。

當您在產品定義中編寫<many-to-one name="supplier" class="Supplier" column="supplierId"/>時,您將supplierId定義爲Product類中的字段。

在Supplier類中,您告訴Hibernate,對於products集合,Product類中外鍵的名稱是supplierId

當您執行您的HQL語句時,Hibernate會將這些信息轉換爲「ON p.supplierId = s.id」sql子句。

+0

Awww我怎麼可能錯過了這個.. 你現在已經知道我現在有多尷尬。 永遠不會少..感謝您的好解釋! 它讓一些事情變得更清晰!謝謝! –

2

在列的

<many-to-one name="supplier" class="Supplier" column="supplierId"/> 

值定義在產品表的外鍵列的名稱。外鍵包含供應商表的一些主鍵值。 本專欄將實現數據庫中產品與供應商之間的關係。沒有這樣的專欄,數據庫中的產品和供應商之間就沒有關係。然後Bag就是這個關係的反面。

類似的情況可以從Hibernate documentation找到。

+0

感謝您的好解釋!尷尬,我錯過了「細節」..但感謝您的偉大解釋!簡短而清楚..我不知何故真的很困惑;)謝謝你們兩位!祝你今天愉快! –