Table of contents
1.
Introduction 
2.
One-to-One XML Mapping in Hibernate  
2.1.
Persistent classes for One to One mapping
2.1.1.
Customer.java 
2.1.2.
Cars.java
2.1.3.
hibernate.cfg.xml
2.2.
Mapping files for the persistent classes
2.2.1.
customer.hbm.xml
2.2.2.
cars.hbm.xml
2.3.
User classes to store and fetch the data
2.3.1.
Store.java
2.3.2.
Fetch.java
3.
Frequently Asked Questions
3.1.
What is a persistent class? 
3.2.
What are the different types of relationships that can be established between entities in Hibernate?  
3.3.
What is a Component class in Hibernate?
4.
Conclusion
Last Updated: Mar 27, 2024

One-to-One XML

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

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:

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;  
}  
You can also try this code with Online Java Compiler
Run Code

 

Cars.java

package codingninjas;  
  
public class Cars
{  
	private int car_id;  
	private String state;  
	private int number;  
	private Customer customer;   
}   
You can also try this code with Online Java Compiler
Run Code

 

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");    
	}    
}    
You can also try this code with Online Java Compiler
Run Code

 

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");    
	}    
}    
You can also try this code with Online Java Compiler
Run Code

 

Output 

1 Abc Def 999999999
Kerala 7654 
Done 

Frequently Asked Questions

What is a persistent class? 

Persistent classes in Hibernate are Java classes whose objects or instances will be stored in database tables. 

What are the different types of relationships that can be established between entities in Hibernate?  

The different types of relationships that can be established between entities in Hibernate are-

  • One to One 
  • Many to One/One to Many
  • Many to Many  

What is a Component class in Hibernate?

An Entity class may have a reference to another class as a member variable. In case, the referred class does not have a life cycle of its own and it completely depends on the life cycle of the owning entity class, then the referred class is called Component class.   

Conclusion

This article extensively discusses the concept of One-to-One  XML in detail along with the code involved. It also explains the examples in detail to make the concept clear.

To hold a tighter grip on the topic, we recommend reading some more related blogs: XML Interview QuestionsJSON vs XML, and JSP - XML Data.
We hope that this blog has helped you enhance your knowledge regarding One-to-One XML, and if you would like to learn more, check out our articles on Coding Ninjas Blogs
 

You can refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSQLSystem Design, and many more!

If you want to test your competency in coding, you may check out the Mock Test Series and participate in the Contests organized on Coding Ninjas Studio! But if you have just started your learning process and are looking for questions asked by tech giants like Amazon, Microsoft, Uber, etc; you must look at the ProblemsInterview Experiences, and Interview Bundle for placement preparations.

Nevertheless, you may consider our Courses to give your career an edge over others!

Do upvote our blog to help other ninjas grow. 

Happy Coding!

Live masterclass