Introduction
Hibernate Mappings are one of the most significant features of Hibernate. It basically establishes the relationship between two database tables as attributes in the model. which allows easy navigation of the associations in criteria queries and models.
Mappings can be established either bidirectional or unidirectional. In other words, they can be modelled as an attribute on only one of the associated entities or on both. It does not impact the database mapping tables, but it defines in which direction in which the relationship in your model and criteria queries can be used.
There are different kinds of relationships that can be established between entities.
So, in this article, we will discuss One to One relationship in Hibernate using XML.
One-to-One XML Mapping in Hibernate
There are two ways to establish One to One mapping in Hibernate:
-
Using one-to-one element
-
Using many-to-one element
This article is limited to using one-to-one elements for implementing One-to-One mapping in Hibernate. In this way of implementation, the foreign key is not created in the primary table.
For this article, one customer owns one car and a car can belong to only one customer. Here, we will use bidirectional association. Let us have a look at the persistent classes.
Persistent classes for One to One mapping
There are two persistent classes Customer.java and Cars.java. Customer class contains Cars class reference and vice versa.
Customer.java
package codingninjas;
public class Customer
{
private int customer_id;
private String name
private int phone_numer;
private Cars cars;
}
Cars.java
package codingninjas;
public class Cars
{
private int car_id;
private String state;
private int number;
private Customer customer;
}
hibernate.cfg.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 5.3//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">
<hibernate-configuration>
<session-factory>
<property name="hbm2ddl.auto">update</property>
<property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
<property name="connection.url">jdbc:oracle:thin:@localhost:1341:xe</property>
<property name="connection.username">system</property>
<property name="connection.password">jtp</property>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<mapping resource="employee.hbm.xml"/>
<mapping resource="address.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Mapping files for the persistent classes
The two mapping files are customer.hbm.xml and cars.hbm.xml.
customer.hbm.xml
In this mapping file, a one-to-one element will be used in both the mapping files to make the One-to-One mapping.
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 5.3//EN" "http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">
<hibernate-mapping>
<class name="codingninjas.Customer" table="cust">
<id name="customer_id">
<generator class="increment"></generator>
</id>
<property name="name"></property>
<property name="phone_number"></property>
<one-to-one name="cars" cascade="all"></one-to-one>
</class>
</hibernate-mapping>
cars.hbm.xml
This is the simple mapping file for the Cars class. Note that we are using the generator class. Here, a foreign generator class that depends on the Customer class primary key. Is being used.
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 5.3//EN" "http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">
<hibernate-mapping>
<class name="codingninjas.cars" table="carst">
<id name="car_id">
<generator class="foreign">
<param name="property">Customer</param>
</generator>
</id>
<property name="state"></property>
<property name="number"></property>
<one-to-one name="customer"></one-to-one>
</class>
</hibernate-mapping>
User classes to store and fetch the data
Store.java
package codingninjas;
import org.hibernate.*;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
public class Store
{
public static void main(String[] args)
{
StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();
Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();
SessionFactory factory=meta.getSessionFactoryBuilder().build();
Session session=factory.openSession();
Transaction t=session.beginTransaction();
Customer cust1=new Customer();
cust1.setName("Abc Def");
cust1.setPhno(999999999);
Cars car1=new Cars();
car1.setState("Kerala");
car1.setNumber(7654);
cust1.setCars(car1);
car1.setCustomer(cust1);
session.persist(cust1);
t.commit();
session.close();
System.out.println("Successful");
}
}
Output
Successful
Fetch.java
package codingninjas;
import java.util.*;
import javax.persistence.TypedQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
public class Fetch
{
public static void main(String[] args)
{
StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();
Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();
SessionFactory factory=meta.getSessionFactoryBuilder().build();
Session session=factory.openSession();
TypedQuery query=session.createQuery("from Customer c");
List<Customer> list=query.getResultList();
Iterator<Customer> itr=list.iterator();
while(itr.hasNext())
{
Customer c1=itr.next();
System.out.println(c1.getCustomerId()+" "+emp.getName()+" "+emp.getNumber());
Cars car1=c1.getCars();
System.out.println(car1.getCarId()+" "+car1.getState()+" "+
car1.getNumber());
}
session.close();
System.out.println("Done");
}
}
Output
1 Abc Def 999999999
Kerala 7654
Done




