Table of contents
1.
Introduction
2.
Environment Setup for HB Using XML
3.
Creating HB Using XML Application
3.1.
Create the java project
3.2.
Include Hibernate Jar Files
3.3.
Create a Persistent Class
3.4.
Creating the Mapping File for the Persistent Class
3.5.
Create the Configuration File
3.6.
Creating the Class that Retrieves or Stores the Persistent Object
3.7.
Run the Application
4.
Frequently Asked Questions
4.1.
How does hibernation work?
4.2.
What is XML?
4.3.
What exactly is hibernate cfg XML?
5.
Conclusion
Last Updated: Mar 27, 2024
Medium

HB Using XML

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

Introduction

Hibernate lets you work with persistent XML data in the same way that you do with persistent POJOs. Instead of POJOs, a parsed XML tree can be considered another way of representing relational data at the object level. Hibernate provides support for the dom4j API for manipulating XML trees.

In this article, we will discuss HB using XML. Here we will create a simple hibernate application using the Eclipse IDE. We typically use XML mapping files in hibernate to transform data from POJO classes to databases and vice versa.

Environment Setup for HB Using XML

To begin, ensure that you are running JDK 5.0; if not, you must upgrade to JDK 5.0 to take advantage of the built-in annotation support.

Afterward, install the Hibernate 3.x annotations distribution package and add hibernate.jar, lib/hibernate.jar, and lib/ejb3-persistence.jar to your CLASSPATH.

Creating HB Using XML Application

To create HB using XML, we are going to follow the following steps:

  1. Create the java project.
  2. Include hibernate jar files.
  3. Create a Persistent class.
  4. Creating the mapping file for the Persistent class.
  5. Create the configuration file.
  6. Creating the class that retrieves or stores the persistent object.
  7. Run the application.

Create the java project

Create a java project by selecting File - New - Project - Java Project. Now enter the project name, for example, Coding_ninjas_HB using XML, followed by next - finish.

Include Hibernate Jar Files

To include the jar files, Right-click your project and select Build path -> Add external archives. Now, as shown in the image below, select all jar files and click open.

include jar files

Create a Persistent Class

To create the persistent class, right-click on src - New - Class - name the class (for e.g. com.codingninjas.mypackage) - finish.

ninja.java

package com.codingninjas.mypackage;  
  
public class Ninja{  
private int id;  
private String firstName,lastName;  
  
public int getId() {  
    return id;  
}  
public void setId(int id) {  
    this.id = id;  
}  
public String getFirstName() {  
    return firstName;  
}  
public void setFirstName(String firstName) {  
    this.firstName = firstName;  
}  
public String getLastName() {  
    return lastName;  
}  
public void setLastName(String lastName) {  
    this.lastName = lastName;  
}  
}  

Creating the Mapping File for the Persistent Class

To create the mapping file, right-click on src - new - file - name the file (ninja.hbm.xml) - click OK. It must be located outside of the package.

Ninja.hbm.xml

<?XML version='1.0' encoding='UTF-8'?>  
<!DOCTYPE hibernate-mapping PUBLIC  
 "//Hibernate/Hibernate Mapping DTD 5.3//EN"  
 "https://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">  
  
 <hibernate-mapping>  
  <class name="com.codingninjas.mypackage.ninja" table="nin1000">  
    <id name="id">  
     <generator class="assigned"></generator>  
    </id>  
            
    <property name="firstName"></property>  
    <property name="lastName"></property>  
            
  </class>  
            
 </hibernate-mapping>

Create the Configuration File

The configuration file contains all database information such as connection URL, driver class, username, password, etc. The hbm2ddl.auto property is used to create the table in the database automatically. To make the configuration file, right-click on src - new - file. Now enter the name of the configuration file, for example, hibernate.cfg.xml.

Hibernate.cfg.xml

<?xml version='1.0' encoding='UTF-8'?>  
<!DOCTYPE hibernate-configuration PUBLIC  
          "//Hibernate/Hibernate Configuration DTD 5.3//EN"  
          "https://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">  
  
<hibernate-configuration>  
  
    <session-factory>  
        <property name="hbm2ddl.auto">update11</property>  
        <property name="dialect">org.hibernate.dialect.Oracle9Dialect1</property>  
        <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>  
        <property name="connection.username">system1</property>  
        <property name="connection.password">oracle1</property>  
        <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver1</property>  
    <mapping resource="ninja.hbm.xml"/>  
    </session-factory>  
  
</hibernate-configuration>  

Creating the Class that Retrieves or Stores the Persistent Object

This class simply stores the ninja object in the database.

package com.codingninjas.mypackage;  
  
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.SessionFactory;    
import org.hibernate.boot.MetadataSources;  
import org.hibernate.boot.Metadata;  
import org.hibernate.boot.registry.StandardServiceRegistryBuilder; 
import org.hibernate.boot.registry.StandardServiceRegistry;   
  
public class StoreData {  
  
    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();  
          
         ninja1=new ninja();    
            e1.setId(1);    
            e1.setFirstName("Alankrit");    
            e1.setLastName("Srivastava");    
         
       session.save(e1);  
       t.commit();  
       System.out.println("successfully saved");    
        factory.close();  
        session.close();     
    }  
} 

Run the Application

Determine the directory structure before running the application.

Directory Structure

Right-click on the StoreData class and select Run As - Java Application to run the hibernate (HB using XML) application.

Frequently Asked Questions

How does hibernation work?

Hibernate handles the mapping of Java classes to database tables using XML files without the need for any code.

What is XML?

XML stands for Extensible Markup Language. It is a markup language that is very much similar to HTML but lacks predefined tags. Instead, we create our own tags that are according to our specific requirements. This is a very effective method for storing data in a particular format that can be stored, searched, and shared.

What exactly is hibernate cfg XML?

Hibernate Configuration File (cfg file) is the file that is loaded into a hibernate application when using hibernate. This file is then used by Hibernate to connect to the database server. It is an XML file that contains the information listed below. This file is commonly referred to as hibernate.

Conclusion

In this article, we have extensively discussed HB using XML. We had created an HB using XML application which brushed up our understanding in a better way about hibernating and HB using XML.

If you think this blog has helped you enhance your knowledge about hibernating and HB using XML, and if you would like to learn more, check out our articles on hibernate architectureHB Generator classeshibernate sessions, and hibernate annotations. You can also refer to our guided path on the basics of java and many more on our Website.

Refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingJavaScriptSystem 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 hosted on Coding Ninjas Studio! 

But suppose you have just started your learning process and are looking for questions asked by tech giants like Amazon, Microsoft, Uber, etc. In that case, you must look at the problemsinterview experiences, and interview bundle for placement preparations.

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

Happy Learning!

Live masterclass