Hi,
I was having problem getting hibernate ddl to generate foreign key constraint on the referencing entity on tables with shared primary key.
I started out with an example as follows:
Code:
@Entity
public class Employee {
@Id @GeneratedValue(strategy=GenerationType.AUTO)
Integer id;
@OneToOne
@PrimaryKeyJoinColumn
EmployeeInfo info;
}
@Entity
public class EmployeeInfo {
@Id Integer id;
}
Employee is the referenced table and EmployeeInfo is referencing the Employee table where both tables have shared primary keys.
I thought that a foreign key constraint on Employee.id should be placed on the EmployeeInfo.id as indicated by the @PrimaryKeyJoinColumn on Employee.
However, the foreign key constraint on EmployeeInfo table is not generated by hibernate ddl as I expected it to be.
I found this thread and deviced the following workaround:
Code:
@Entity
public class Employee {
@Id @GeneratedValue(strategy=GenerationType.AUTO)
Integer id;
@OneToOne
@PrimaryKeyJoinColumn
EmployeeInfo info;
}
@Entity
public class EmployeeInfo {
@Id
@Column(name="id", updatable=false, unique=true) // does not allow
Integer id;
//Must use optional=false to force generate the foreign key constraint
@OneToOne(optional=false)
@PrimaryKeyJoinColumn(name="id", referencedColumnName="id")
Employee employee;
}
To save and associate both entities, we will need to save Employee and EmployeeInfo
in the following order:
Code:
Employee employee = new Employee();
em.persist(employee);
EmployeeInfo info = new EmployeeInfo();
info.id = employee.id;
employee.info = info;
info.employee = employee;
em.persist(info);
em.refresh(employee);
This will create the EmployeeInfo table with a foreign key constraint on EmployeeInfo.id to Employee.id, which is what I want.
Is this the expected behaviour with respect to the JPA specification, specifically should @PrimaryKeyJoinColumn cause the foreign key constraint on the referencing table to be generate by default?
Thanks