You have a 1-to-1 relationship when an object of a class has an associated object of another class (only one associated object). It could also be between an object of a class and another object of the same class (obviously). You can create the relationship in 2 ways depending on whether the 2 classes know about each other (bidirectional), or whether only one of the classes knows about the other class (unidirectional). These are described below.
For this case you could have 2 classes,
User
and
Account
, as below.
<entity-mappings>
<entity class="User">
<table name="USER"/>
<attributes>
<id name="id">
<column name="USER_ID"/>
</id>
...
</entity>
<entity class="Account">
<table name="ACCOUNT"/>
<attributes>
<id name="id">
<column name="ACCOUNT_ID"/>
</id>
...
<one-to-one name="user">
<join-column name="USER_ID"/>
</one-to-one>
</attributes>
</entity>
</entity-mappings>or alternatively using annotations
public class Account
{
...
@OneToOne
@JoinColumn(name="USER_ID")
User user;
}
public class User
{
...
}
This will create 2 tables in the database, one for
User
(with name
USER
), and one for
Account
(with name
ACCOUNT
and a column
USER_ID
), as shown below.
Things to note :-
For this case you could have 2 classes, User and Account again, but this time as below. Here the Account class knows about the User class, and also vice-versa.
We create the 1-1 relationship with a single foreign-key. To do this you define the XML metadata as
<entity-mappings>
<entity class="User">
<table name="USER"/>
<attributes>
<id name="id">
<column name="USER_ID"/>
</id>
...
<one-to-one name="account" mapped-by="user"/>
</attributes>
</entity>
<entity class="Account">
<table name="ACCOUNT"/>
<attributes>
<id name="id">
<column name="ACCOUNT_ID"/>
</id>
...
<one-to-one name="user">
<join-column name="USER_ID"/>
</one-to-one>
</attributes>
</entity>
</entity-mappings>or alternatively using annotations
public class Account
{
...
@OneToOne
@JoinColumn(name="USER_ID")
User user;
}
public class User
{
...
@OneToOne(mappedBy="user")
Account account;
...
}
This will create 2 tables in the database, one for User (with name USER ), and one for Account (with name ACCOUNT ). For RDBMS it includes a USER_ID column in the ACCOUNT table, like this
For other types of datastore it will have a USER_ID column in the ACCOUNT table and a ACCOUNT column in the USER table. Things to note :-
|