OneToOne mapping to an Entity from multiple owning entities

admin

Administrator
Staff member
I am a JPA newbie. I have what I believe is a very simple example, but I am having trouble implementing it. Basically, I have an entity that I want to "reuse" in other entities.

I have a
Code:
User
having two fields -
Code:
Home
and
Code:
Office
. Each of these in turn refers to an
Code:
Address
, like so:

Code:
@Entity
public class User extends Model {

    @Column 
    private String name;

    @OneToOne
    private Home home;

    @OneToOne
    private Office office;

}

@Entity
public class Home extends Model {

    @OneToOne
    private Address address;

    @OneToOne(mappedBy="home")
    private User user;

    // ...

}

@Entity
public class Office extends Model {

    @OneToOne
    private Address address;

    @OneToOne(mappedBy = "office")
    private User user;

    // ...
}

@Entity
public class Address extends Model {

    @Column
    private String line1;

    @Column 
    private String line2;

    @Column
    private String city;

    /*
     * Is this possible? Being owned by two entities?
     */


    @OneToOne(mappedBy="address")
    private Home home;

    @OneToOne(mappedBy="address")
    private Office office;

    // ...
}

How do I achieve this?

<hr>

<h2>EDIT</h2>

I was originally running into this exception:

Code:
org.hibernate.AnnotationException: @OneToOne or @ManyToOne on example.Home.address references an unknown entity: example.Address

It turns out that one of the classes had imported the
Code:
@Entity
annotation from
Code:
org.hibernate
instead of from
Code:
javax.persistence
. After fixing this, the original exception went away (<a href="http://techazizhk.wordpress.com/200...-references-an-unknown-entity-xxx/#comment-75" rel="nofollow">this</a> helped me pin point the issue)

However, I now have a new exception:

Code:
org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: example.User.home -&gt; example.Home

I don't quite understand this exactly. Should I call
Code:
save
the
Code:
Home
object before I do so on the
Code:
User
instance?