Ammar
Ammar

Reputation: 1821

Hibernate one-to-one mapping

I'm facing a problem in hibernate one to one mapping. Googled a lot but unable to solve.

Here is database

Following are my model classes.

public class User {

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;
}

}

and

public class Address {

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 is as following:

<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 is as below,

<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>

On running, following exception occurs:

Exception in thread "main" org.hibernate.HibernateException: Unable to resolve property: addrId

Runs fine without mapping. But can't retrieve records when mapping applied.

The query printed by hibernate runs perfectly fine in DB.

Upvotes: 0

Views: 1473

Answers (2)

Jim
Jim

Reputation: 3694

In user.hbm.xml property-ref="addrId" should be property-ref="userId" because the property-ref is talking about how to connect an Address to a User, not the other way around, which is confusing. You can probably leave out property-ref, since without it Address will find the User via the foreign key pointing at the primary key. The docs say "If not specified, the primary key of the associated class is used" (section 5.1.13).

Upvotes: 2

Alex
Alex

Reputation: 2146

I don't think it's working with int values... I thing they have to be Integer...

can you change like this?:

private int addrId;

into

private Integer addrId;

and so on for all int variables...

Upvotes: 0

Related Questions