Hibernate Example using XML in Eclipse
Hibernate is a framework that provides some abstraction layer, meaning that the programmer does not have to worry about the implementations, Hibernate does the implementations for you internally like Establishing a connection with the database, writing queries to perform CRUD operations, etc. In this article, let us see a Hibernate Example using XML along with MySQL database in eclipse.
Requirements:
- Eclipse
- Maven
- Hibernate
- MySQL
- JDK 6 onwards
Example
As we are going to check about the maven kind of project, let us see the pom.xml
XML
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 < modelVersion >4.0.0</ modelVersion > < groupId >com.geeksforgeeks</ groupId > < artifactId >HibernateSampleExample</ artifactId > < packaging >jar</ packaging > < version >1.0-SNAPSHOT</ version > < name >HibernateSampleExample</ name > < dependencies > < dependency > < groupId >junit</ groupId > < artifactId >junit</ artifactId > < version >3.8.1</ version > < scope >test</ scope > </ dependency > < dependency > < groupId >org.hibernate</ groupId > < artifactId >hibernate-core</ artifactId > < version >4.3.5.Final</ version > </ dependency > < dependency > < groupId >mysql</ groupId > < artifactId >mysql-connector-java</ artifactId > < version >5.1.6</ version > </ dependency > </ dependencies > < build > < pluginManagement > < plugins > < plugin > < groupId >org.apache.maven.plugins</ groupId > < artifactId >maven-compiler-plugin</ artifactId > < version >3.1</ version > < configuration > < source >1.7</ source > < target >1.7</ target > </ configuration > </ plugin > </ plugins > </ pluginManagement > </ build > </ project > |
For Hibernate, we should keep the details on the “hibernate.cfg.xml” file which specifies what kind of database and its credentials, its required drivers, etc., are placed. In this example, we are going to use MySQL and hence
hibernate.connection.driver_class = com.mysql.jdbc.Driver
The advantage of hibernate is it will create a mapping of a database table with a Java application class file. That is also specified in an XML file. Let us create a table in MySQL first
-- Here "geeksforgeeks" is the name of the database -- "GeekUserDetails" is the name of the table -- geekUserId is the Primary Key CREATE TABLE geeksforgeeks.GeekUserDetails ( geekUserId INT (5) NOT NULL, geekUsername VARCHAR (20) NOT NULL, numberOfPosts INT(5) NOT NULL, CREATED_BY VARCHAR (20) NOT NULL, CREATED_DATE DATE NOT NULL, PRIMARY KEY ( geekUserId ) )
Let us see the mapping file in Hibernate. i.e. each and every column has to be mapped between a table and class. First, let us create POJO(Model class) in Java for that
Java
import java.util.Date; // We can check that column name in "GeekUserDetails" is // matching with each and every field here. It is always good // to have the same column name and field name here public class GeekUserDetails { private int geekUserId; private String geekUsername; private int numberOfPosts; public int getNumberOfPosts() { return numberOfPosts; } public int getGeekUserId() { return geekUserId; } public void setGeekUserId( int geekUserId) { this .geekUserId = geekUserId; } public String getGeekUsername() { return geekUsername; } public void setGeekUsername(String geekUsername) { this .geekUsername = geekUsername; } public void setNumberOfPosts( int numberOfPosts) { this .numberOfPosts = numberOfPosts; } private String createdBy; private Date createdDate; public String getCreatedBy() { return createdBy; } public void setCreatedBy(String createdBy) { this .createdBy = createdBy; } public Date getCreatedDate() { return createdDate; } public void setCreatedDate(Date createdDate) { this .createdDate = createdDate; } } |
Now, the mapping file related to the POJO file.
resources/geekuser.hbm.xml
XML
<? xml version = "1.0" encoding = "UTF-8" ?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" < hibernate-mapping > <!-- com.geeksforgeeks.GeekUserDetails is the name of the java class GeekUserDetails is the name of the table --> < class name = "com.geeksforgeeks.GeekUserDetails" table = "GeekUserDetails" > < id name = "geekUserId" type = "int" column = "geekUserId" > < generator class = "assigned" /> </ id > < property name = "geekUsername" > < column name = "geekUsername" /> </ property > < property name = "numberOfPosts" type = "int" > < column name = "numberOfPosts" /> </ property > < property name = "createdBy" > < column name = "CREATED_BY" /> </ property > < property name = "createdDate" type = "date" > < column name = "CREATED_DATE" /> </ property > </ class > </ hibernate-mapping > |
Now, let us see the main configuration file
resources/hibernate.cfg.xml
XML
<? xml version = "1.0" encoding = "utf-8" ?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" <!-- Main configuration file --> < hibernate-configuration > < session-factory > <!-- As we are connecting MySQL, com.mysql.jdbc. Driver is required(JDBC driver class) --> < property name = "hibernate.connection.driver_class" >com.mysql.jdbc.Driver</ property > <!-- Here geeksforgeeks is the name of the database that we are connecting(JDBC URL) --> <!-- Username to connect to MySQL --> < property name = "hibernate.connection.username" >root</ property > <!-- Password to connect to MySQL, Provide your correct password --> < property name = "hibernate.connection.password" >XXXX</ property > <!-- Dialect required between hibernate and MySQL --> <!-- This property makes Hibernate generate the appropriate SQL for MySQL here --> < property name = "hibernate.dialect" >org.hibernate.dialect.MySQLDialect</ property > < property name = "show_sql" >true</ property > < property name = "format_sql" >true</ property > < property name = "hbm2ddl.auto" >update </ property > <!-- We need to provide the exact mapping file which we have created earlier --> < mapping resource = "geekuser.hbm.xml" /> </ session-factory > </ hibernate-configuration > |
After creating the mapping between the MySQL table and Java class via “geekuser.hbm.xml” and “hibernate.cfg.xml”, let us try to do a simple insertion of a record in the table Let us try to run that via a java application file. We need to look upon certain files like HibernateUtil.java. We need to create the SessionFactory from hibernate.cfg.xml. Hence first all the entries in this XML have to be satisfied before entering into the main code. Otherwise need to provide the required code to throw the exception.
Java
import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernateUtil { private static final SessionFactory sessionFactory = buildSessionFactory(); private static SessionFactory buildSessionFactory() { try { // We need to create the SessionFactory from // hibernate.cfg.xml return new Configuration() .configure() .buildSessionFactory(); } catch (Throwable ex) { // Make sure you log the exception, as it might // be swallowed // In case of any exception, it has to be // indicated here System.err.println( "SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory() { return sessionFactory; } public static void shutdown() { // Close caches and connection pools getSessionFactory().close(); } } |
GeekUserDetailsTest.java -> Session is getting created by using HibernateUtil.java. Hibernate SessionFactory has three methods namely getCurrentSession(), openSession() and openStatelessSession(). In our code, we are using openSession(). If it is not given, we will get into exception as Exception in thread “main” org.hibernate.HibernateException: No CurrentSessionContext configured! For openSession(), it will always open a new session and it has to be closed
Java
import java.util.Date; import org.hibernate.Session; public class GeekUserDetailsTest { public static void main(String[] args) { // open the session Session session = HibernateUtil.getSessionFactory().openSession(); // For doing any CRUD operation, // let us start a transaction session.beginTransaction(); // Create an object of GeekUserDetails GeekUserDetails geekUser = new GeekUserDetails(); // Set all the details required // to insert into the table geekUser.setGeekUserId( 1 ); geekUser.setGeekUsername( "GeekUser1" ); geekUser.setNumberOfPosts( 100 ); geekUser.setCreatedBy( "GeekUser1" ); geekUser.setCreatedDate( new Date()); // Just a save statement is enough which // automatically creates an insert statement session.save(geekUser); // commit will help to complete // the changes in the table session.getTransaction().commit(); // close the session session.close(); } } |
Once this file is run as a “Java application”, we can able to see a record is inserted into the “GeekUserDetails” table
Video explanation about the code:
Conclusion
Using hibernate.cfg.xml (main XML file defining the database JDBC details, SQL dialects, etc.,) a mapping file that maps the columns of a table and a POJO class. (Here it is geekuser.hbm.xml) we can do all the CRUD operations easily in Hibernate.
Please Login to comment...