One to One Mapping Examples in Hibernate
Association mappings are one of the key features of JPA and Hibernate.
They model the relationship between two database tables as attributes in your domain model. That allows you to easily navigate the associations in your domain model and JPQL or Criteria queries.
JPA and Hibernate support the same associations as you know from your relational database model. You can use:
1). one-to-one associations,
2). many-to-one associations and
3). many-to-many associations.
In this tutorial, we will see one to one mapping with different approaches.
We have two entities here: Student and Address.
One Student can have only one Address. Similarly, an address will be associated with one student only. It's one to one relationship for this example.
Hibernate one to one mapping with foreign key association
In this association, a foreign key column is created in the owner entity.
Here if we make Student as the owner, additional column "address_id" will be created in the Student table. This column will store the foreign key for the Address table.
@OneToOne
@JoinColumn(name="address_id")
private Address address;
If no @JoinColumn is declared on the owner side, the defaults apply. A join column(s) will be created in the owner table and its name will be the concatenation of the name of the relationship in the owner side, _ (underscore), and the name of the primary key column(s) in the owned side.
@JoinColumn is like normal @Column annotation. It has one more parameter named referencedColumnName. This parameter declares the column in the targeted entity that will be used to join.
@OneToOne(mappedBy = "address")
private Student student;
try {
transaction = session.beginTransaction();
Address address1 = new Address("F C Road", "Pune", "MH", "411005");
Student student1 = new Student("Bala", address1);
session.address1(student1);
session.save(student1);
transaction.commit();
} catch(HibernateException e) {
transaction.rollback();
e.printStackTrace();
} finally {
session.close();
}
Hibernate one to one mapping with common join table
In this approach, we need to use @JoinTable. This annotation is used to define the new table name (mandatory) and foreign keys from both of the tables.
@OneToOne(cascade = CascadeType.ALL)
@JoinTable(name="student_address", joinColumns = @JoinColumn(name="address_id"),
inverseJoinColumns = @JoinColumn(name="student_id"))
private Address address;
@JoinTable annotation is used in the Student class. It declares that a new table student_address will be created with two columns student_id (primary key of Student table) and address_id (primary key of Address table).
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
public class App {
public static void main(String[] args) {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
Address address1 = new Address("F C Road", "Pune", "MH", "411005");
Address address2 = new Address("J M Road", "Pune", "MH", "411004");
Student student1 = new Student("Bala", address1);
Student student2 = new Student("Dyana", address2);
session.save(student1);
session.save(student2);
transaction.commit();
} catch(HibernateException e) {
transaction.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
}
Hibernate one to one mapping with the shared primary key
In this approach, the hibernate will ensure that it will use a common primary key value in both the tables. This way the primary key of the Student can safely be assumed as the primary key of the Address also.
So the entry in the Student.java is like
@OneToOne(cascade = CascadeType.ALL)
@PrimaryKeyJoinColumn
private Address address;
Hibernate one to one mapping with @MapsId
In this approach, the hibernate assumes both the source and target share the same primary key values.
In this approach, @MapsId is the main annotation to be used.
In Student.java we have
@Entity(name = "MapsByIdStudent")
@Table(name = "Student", uniqueConstraints = {
@UniqueConstraint(columnNames = "id") })
public class EmployeeEntity implements Serializable {
{
@Id@GeneratedValue@Column(name = "id")
private long id;
@Column(name = "name")
private String name;
@OneToOne@MapsId
private Address address;
//@Getters
//@Setters
}
Address.java is
@Entity(name = "MapsByIdAddress")
@Table(name = "address", uniqueConstraints = {@UniqueConstraint(columnNames = "id")})
public class Address implements Serializable
{
@Id@GeneratedValue@Column(name = "id")
private long id;
@Column(name = "street", nullable = false, length = 250)
private String street;
@Column(name = "city", nullable = false, length = 50)
private String city;
@Column(name = "state", nullable = false, length = 50)
private String state;
@Column(name = "zip", nullable = false, length = 10)
private String zipcode;
//@Getters
//@Setters
}
In this article, we have seen One to One Mapping Examples in Hibernate. All source code in the article can be found in the GitHub repository.
0 Comments
Post a Comment