Here’s a simple example of how to share primary keys between two persistent entities having one-to-one association. We’ll have a User entity which has one address. Here’s the User POJO:

public class User {
    Long id;
    Address address;
    String username;

    public User() {
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }
}

And here’s the Address entity POJO:

public class Address {

    Long id;
    String address;
    User user;

    public Address() {
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
}

Now the Hibernate mapping for user looks like:

<hibernate-mapping>
    <class name="com.jft.prashant.User"
           table="USERS" >

        <id name="id" column="USER_ID">
            <generator class="native" />
        </id>

        <property name="username"
                  column="USERNAME"
                  type="string"
                  not-null="true"/>


        <one-to-one name="address"
                    class="com.jft.prashant.Address"
                    cascade="save-update,delete" />
    </class>
</hibernate-mapping>

and Hibernate mapping for Address looks like:

<hibernate-mapping>
    <class name="com.jft.prashant.Address"
           table="ADDRESSES">

        <id name="id" column="ADDRESS_ID">
            <generator class="foreign">
                <param name="property">user</param>
            </generator>
        </id>

        <property name="address"
                  type="string"
                  column="ADDRESS"
                  not-null="true"/>

        <one-to-one name="user"
                    class="com.jft.prashant.User"
                    constrained="true"/>
    </class>
</hibernate-mapping>

Key points are:

  1. one-to-one mapping in the Address makes the association bidirectional and with constrained=true adds the foreign key constraint linking the primary key of the ADDRESS table to the primary key of USERS table. It also guarantees that an ADDRESS row’s primary key references a valid USERS primary key.
  2. Above mentioned constrained=true also helps in creating the proxy of user for address.
  3. generator class=”foreign” and property set to user ensures that the primary key value is taken from the user property and the user property is the reference to the User object.