2012-04-09 159 views
0

我在休眠一對一映射時遇到了一個問題。 Google搜索了很多,但無法解決。休眠一對一映射

這裏是數據庫

http://www.freeimagehosting.net/newuploads/55avs.png

以下是我的模型類

公共類用戶{

private int userId; 
private String userName; 
private Address address; 

public Address getAddress() { 
    return address; 
} 
public void setAddress(Address address) { 
    this.address = address; 
} 
public int getUserId() { 
    return userId; 
} 
public void setUserId(int userId) { 
    this.userId = userId; 
} 

public String getUserName() { 
    return userName; 
} 
public void setUserName(String userName) { 
    this.userName = userName; 
} 

}

公共類地址{

private int addrId; 
private String addr; 

public int getAddrId() { 
    return addrId; 
} 
public void setAddrId(int addrId) { 
    this.addrId = addrId; 
} 
public String getAddr() { 
    return addr; 
} 
public void setAddr(String addr) { 
    this.addr = addr; 
} 

}

user.hbm.xml是如下:

<class name="User" table="users" schema="dbo" catalog="test"> 
     <id name="userId" type="int" column="userId" > 
     <generator class="assigned"/> 
     </id> 

     <property name="userName"> 
     <column name="userName" /> 
     </property> 

     <one-to-one name="address" property-ref="addrId" class="Address" cascade="all" /> 

    </class> 

address.hbm.xml是如下,

<class name="ammar.Address" table="Address" schema="dbo" catalog="test"> 

     <id name="addrId" type="int" column="AddrID" > 
     <generator class="assigned"/> 
     </id> 

     <property name="addr"> 
     <column name="Addr" /> 
     </property> 

    </class> 

在運行時,發生以下情況除外:

例外線程「main」org.hibernate.HibernateException:無法解析屬性:addrId

運行正常,沒有映射。但在應用映射時無法檢索記錄。

由hibernate打印的查詢在DB中運行得非常好。

+0

您需要提供更多詳細信息。 addrId的getter和setter,Address的映射文件,兩者的sql結構。 – Jim 2012-04-09 15:46:34

+0

我編輯提供的細節,如你所說。 – Ammar 2012-04-09 17:10:29

回答

2

在user.hbm.xml中property-ref="addrId"應該是property-ref="userId",因爲property-ref正在討論如何將地址連接到用戶,而不是相反,這是令人困惑的。你可能會遺漏property-ref,因爲沒有它,Address會通過指向主鍵的外鍵找到User。 docs表示「如果未指定,則使用關聯類的主鍵」(5.1.13節)。

+0

我刪除了property-ref屬性,它的工作原理。謝謝吉姆。 – Ammar 2012-04-10 03:41:39

0

我不認爲它的工作與int價值觀......我的事情,他們必須Integer ...

你可以改變這樣的?:

private int addrId; 

private Integer addrId; 

等等全部int變量...

+0

問題不在於int。單獨與用戶或地址一起完成時,它可以正常工作。問題在於映射。即這裏<一對一名稱=「地址」屬性 - ref =「addrId」class =「地址」級聯=「所有」/> – Ammar 2012-04-09 16:55:30