توسط PrimaryKeyJoinColumn@ میتوان از primary key id یک جدول استفاده کرد به عنوان یک foreign key برای join زدن به یک جدول دیگر و برای رابطه OneToOne@ استفاده کرد. به عنوان مثال :
<< Biography class //
import javax.persistence.*;
@Entity
@Table(name="biographies")
public class Biography {
@Id
@Column(name="author_id")
private Integer authorId;
private String information;
public Integer getAuthorId() {
return authorId;
}
public void setAuthorId(Integer authorId) {
this.authorId = authorId;
}
public String getInformation() {
return information;
}
public void setInformation(String information) {
this.information = information;
}
}
>>
<< Author class //
import javax.persistence.*;
@Entity
@Table(name="authors")
public class Author {
@Id
@GeneratedValue
private Integer id;
private String name;
@OneToOne(cascade=CascadeType.ALL)
@PrimaryKeyJoinColumn
private Biography biography;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Biography getBiography() {
return biography;
}
public void setBiography(Biography biography) {
this.biography = biography;
}
}
حالا نحوه استفاده در کد :
public static void main(String[] args) {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
Author author = new Author();
author.setName("full name");
session.persist(author);
Biography biography = new Biography();
biography.setInformation("some information. ......");
biography.setAuthorId(author.getId());
author.setBiography(biography);
session.save(author);
session.getTransaction().commit();
session.close();
}