Hibernate version: 3.2 and Annotations 3.3.0GA
Name and version of the database you are using: Oracle 10g
I am trying to build a OneToOne relationship where the join is based on a non-primary key field of the referencing entity.
For example, there is an EMPLOYEE table with a PK column named EMP_ID and a unique column called SSN. There is also an ADDRESS table with a PK called ADDRESS_ID and a unique column called EMP_SSN. The employee SSN field is used to join to the EMP_SSN field in the ADDRESS table.
I have built the following example below and it works as a unidirectional relationship, but is this the correct way of doing this? Reading thru the forum and the Java Persitence with Hibernate book (pg 283) it sounds like ManyToOne could be used.
The issue I am having is making this bidirectional?
So my questions are:
1) Should this be a OneToOne or a ManyToOne?
2) How can I make this bidirectional?
The tables used are listed below and join on EMPLOYEE.SSN = ADDRESS.EMP_SSN.
Note that I cannot change the design of the database.
Code:
create table EMPLOYEE (
EMP_ID number(19,0) not null,
SSN varchar2(255 char),
NAME varchar2(255 char),
primary key (EMP_ID),
unique (SSN)
)
create table ADDRESS (
ADDRESS_ID number(19,0) not null,
EMP_SSN varchar2(255 char),
STREET varchar2(255 char),
primary key (ADDRESS_ID),
unique (EMP_SSN)
)
Below are the classes and their mapping.
The Employee class has a reference to the Address class.
I would like to make this bidirectional so the Employee class can be referenced from the Address class.
Code:
/** The employee class **/
@Entity
@Table(name="EMPLOYEE")
public class Employee implements java.io.Serializable
{
@Id
@Column(name="EMP_ID")
@GeneratedValue(strategy=GenerationType.SEQUENCE)
public long empID;
@Column(name="NAME")
public String name;
@Column(name="SSN")
public String SSN;
@OneToOne(cascade=CascadeType.ALL)
@JoinColumn(name="SSN",
referencedColumnName="EMP_SSN",
insertable=false,
updatable=false,
nullable=true)
public Address homeAddress;
}
/** The Address Class **/
@Entity
@Table(name="ADDRESS")
public class Address implements java.io.Serializable
{
@Id
@Column(name="ADDRESS_ID")
@GeneratedValue(strategy=GenerationType.SEQUENCE)
public long addressID;
@Column(name="STREET")
public String street;
@Column(name="EMP_SSN")
public String empSSN;
}
/** Code To Test IT **/
private static void test1() throws Exception
{
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
Transaction tx = session.beginTransaction();
Employee emp = new Employee();
emp.name="Herman Munster";
emp.SSN="111-11-1111";
Address a1 = new Address();
a1.street="1313 Mockingbird Lane";
a1.empSSN=emp.SSN;
emp.homeAddress = a1;
session.saveOrUpdate(emp);
tx.commit();
}