2011-04-13 116 views
1

我面對的使用Hibernate的一個問題。我有3個表:tb_user,tb_book,tb_lending。在tb_lending,我有以下字段:Hibernate映射問題的一個一對一/多對一的一個

  • id_lending - INT(11) - 主鍵
  • id_user - INT(11) - 外鍵
  • id_book - INT(11) - 國外鍵

我也有豆代表表(tb_user和tb_book正在完美工作)。

我tbLending.hbm.xml映射這一領域:

<id name="id" type="java.lang.Integer"> 
     <column name="id_lending" /> 
     <generator class="identity" /> 
    </id> 
    <many-to-one name="userId" class="com.wa2011.beans.UserBean" 
     not-null="true" cascade="all" unique="true" column="id_user" /> 
    <many-to-one name="bookId" class="com.wa2011.beans.BookBean" 
     not-null="true" cascade="all" unique="true" column="id_book" /> 

從業務邏輯的關聯應該是一個對一個,因爲每個id_lending我可以有1個用戶和1本書。但我通過這種方式閱讀了一些論壇,使用多對一的方式,然後聲明unique =「true」。

但是,當我執行query.save我得到以下錯誤:

墳墓拋出:IllegalArgumentException類:com.wa2011.beans.UserBean,財產的getter方法:ID

我真的不知道自tb_book和tb_user以來的問題是什麼,就像我在工作之前所說的那樣是一種魅力。

在LendingBean.java的保存方法是:

public void saveLend(LendingBean lendingBean) { 
    Session session = iniHibernate(); 

    try { 
     session.beginTransaction(); 
     session.save(lendingBean); 
     session.getTransaction().commit(); 

    } catch (Exception e) { 
     System.out.println("Error on registering lend:"); 
     System.out.println(e); 
    } 
} 

此方法由processRequest方法,我與其他豆類/ servlet的千篇一律內的servlet LendingActions調用。

<class name="com.wa2011.beans.LendingBean" table="tb_lending" catalog="wa2011"> 
    <id name="id" type="java.lang.Integer"> 
     <column name="id_lending" /> 
     <generator class="identity" /> 
    </id> 
... 
</class> 

在LeandingBean.java我:

@Stateless 
public class LendingBean { 

    private Integer id; 
    private Integer bookId; 
    private Integer userId; 

... 
} 

你能幫助我,好嗎?

在此先感謝。

+0

你可以把你節省操作碼? – nIKUNJ 2011-04-13 13:22:34

+0

當然!已經做了。如果您需要更多信息,請告訴我。非常感謝。 – LucasM 2011-04-13 13:27:56

回答

0

檢查LendingBean bean的id元素來映射。和映射中一樣嗎?

我覺得你LendingBean應該是這樣的:

@Stateless 
public class LendingBean { 

    private Integer id; 
    private BookBean bookId; 
    private UserBean userId; 

... 
} 
+0

我編輯了我的帖子幷包含這些信息。他們似乎是正確的。再次感謝。 – LucasM 2011-04-13 13:41:57

+0

看看我更新的答案。 – nIKUNJ 2011-04-14 04:14:04

+0

非常感謝!我應該使用對象本身作爲id字段(外鍵)的數據類型嗎?我其實已經改變了一些東西。我會在稍後嘗試您的解決方案。我將所有內容都更改爲註釋,而這次我正在關注一本hibernate的書。 – LucasM 2011-04-19 13:08:52