Hibernate Maven MySQL Hello World example (XML Mapping)

In this tutorial, we will try to write a small hello world program using Hibernate, MySQL and Maven. We will create a Java project using Maven and will then try to add Hibernate on it. [sc name=”Hibernate_Tutorials”] Following are the tools and technologies used in this project.
  1. Java JDK 5 or above
  2. Eclipse IDE 3.2 or above
  3. Maven 3.0 or above
  4. Hibernate 3.0 or above
  5. MySQL 5.0 or above

1. Database Creation

For this tutorial, we will create a simple table “employe” in MySQL. Use following script to create the table.
CREATE TABLE `employee` ( `id` BIGINT(10) NOT NULL AUTO_INCREMENT, `firstname` VARCHAR(50) NULL DEFAULT NULL, `lastname` VARCHAR(50) NULL DEFAULT NULL, `birth_date` DATE NOT NULL, `cell_phone` VARCHAR(15) NOT NULL, PRIMARY KEY (`id`) ) COLLATE='latin1_swedish_ci' ENGINE=InnoDB ROW_FORMAT=DEFAULT AUTO_INCREMENT=606
Code language: SQL (Structured Query Language) (sql)
Thus, following will be the connection string to connect with MySQL.
Connection URL: jdbc:mysql://localhost:3306/tutorial DB Username: root DB Password: <your mysql password>
Code language: JavaScript (javascript)

2. Generate Maven Java project compatible with Eclipse

Open a command prompt and execute following code to generate a Maven Java project.
mvn archetype:generate \ -DgroupId=net.viralpatel.hibernate \ -DartifactId=HibernateHelloWorldXML \ -DarchetypeArtifactId=maven-archetype-quickstart \ -DinteractiveMode=false
Code language: Java (java)
Once you execute above command, a project “HibernateHelloWorldXML” is created. Note that this is a Java project which already has folder structures compatible to Maven. Once this is done, we will convert it to be compatible with Eclipse. For that executes following command on command prompt.
mvn eclipse:eclipse
Code language: Java (java)

3. Import project in Eclipse

Open Eclipse and import the above Java project. File > Import… > General > Existing Projects into Workspace > Choose above Java project Once imported, the folder structure will look like following:

Important:

In case you get following error after importing project in Eclipse: If you are getting this Hibernate Maven Repo error, then you need to define M2_REPO environment variable in eclipse pointing to your local maven repository. Goto Window > Preferences… > Java > Build Path > Classpath Variables > Define new variable M2_REPO pointing to your local maven repository. Once you will define this variable and rebuild the project, the above error will go.

4. Add Hibernate Dependency to Maven pom.xml

Add following dependencies to Maven pom.xml.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>net.viralpatel.hibernate</groupId> <artifactId>HibernateHelloWorldXML</artifactId> <packaging>jar</packaging> <version>1.0-SNAPSHOT</version> <name>HibernateHelloWorldXML</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.10</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate</artifactId> <version>3.2.6.ga</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> </dependencies> </project>
Code language: HTML, XML (xml)
Once we have added these dependencies, we will execute following command so that maven will download required Jar files and add the same to eclipse classpath.
mvn eclipse:eclipse
Code language: Java (java)
The above step is not mandatory. If you have Maven plugin for Eclipse installed in your IDE (Latest eclipse comes with this plugin built-in) you can just enable Maven dependencies by doing Right click on project > Maven > Enable Dependency Management.

5. Add Hibernate Configuration XML

Now our project setup is ready. We will add following Hibernate configuration xml file in /src/main/resources folder. Note that this folder is not present in your project structure. Create a source folder: Right click on Project > New > Source Folder > Give folder name “/src/main/resources/” and click Finish. Copy following file in your project. File: /src/main/resources/hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- Database connection settings --> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://localhost:3306/tutorial</property> <property name="connection.username">root</property> <property name="connection.password"></property> <!-- JDBC connection pool (use the built-in) --> <property name="connection.pool_size">1</property> <!-- SQL dialect --> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <!-- Enable Hibernate's automatic session context management --> <property name="current_session_context_class">thread</property> <!-- Disable the second-level cache --> <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property> <!-- Echo all executed SQL to stdout --> <property name="show_sql">false</property> <property name="hbm2ddl.auto">validate</property> <mapping resource="net/viralpatel/hibernate/Employee.hbm.xml"/> </session-factory> </hibernate-configuration>
Code language: HTML, XML (xml)
One thing we need to make sure in Eclipse is that the Java build path must reflect **/*.xml. Right click on project > Properties > Java Build Path > Source > Add **/*.xml as follow:

6. Add Java source code

File: /src/main/java/net/viralpatel/hibernate/Employee.java
package net.viralpatel.hibernate; import java.sql.Date; public class Employee { private Long id; private String firstname; private String lastname; private Date birthDate; private String cellphone; public Employee() { } public Employee(String firstname, String lastname, Date birthdate, String phone) { this.firstname = firstname; this.lastname = lastname; this.birthDate = birthdate; this.cellphone = phone; } // Getter and Setter methods }
Code language: Java (java)
Above is the Employee POJO class that we will use to fetch data from Employee table. This Java class will be mapped by Hiberate with Employee table. Note that we have define two constructors first default and second with arguements. The second constructor is optional. But note that you must define a default (No-arguement) constructor in your mapping class. File: /src/main/java/net/viralpatel/hibernate/HibernateUtil.java
package net.viralpatel.hibernate; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernateUtil { private static final SessionFactory sessionFactory = buildSessionFactory(); private static SessionFactory buildSessionFactory() { try { // Create the SessionFactory from hibernate.cfg.xml return new Configuration() .configure() .buildSessionFactory(); } catch (Throwable ex) { System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory() { return sessionFactory; } }
Code language: Java (java)
As discussed in previous article Introduction to Hibernate framework, we have to create SessionFactory instance in order to communicate with Database in Hibernate. We will use a Utility class called HibernateUtil to instantiate SessionFactory. File: /src/main/java/net/viralpatel/hibernate/Employee.hbm.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="net.viralpatel.hibernate"> <class name="Employee" table="EMPLOYEE"> <id name="id" column="ID"> <generator class="native"/> </id> <property name="firstname" /> <property name="lastname" column="lastname"/> <property name="birthDate" type="date" column="birth_date"/> <property name="cellphone" column="cell_phone"/> </class> </hibernate-mapping>
Code language: HTML, XML (xml)

7. CRUD operations in Hibernate

Let us see the basic CRUD operation in Hibernate. We will use Employee table for this.

7.1 Writing (Create) data in Hibernate Following is the code snippet that insert a row in database.
private static Employee save(Employee employee) { SessionFactory sf = HibernateUtil.getSessionFactory(); Session session = sf.openSession(); session.beginTransaction(); Long id = (Long) session.save(employee); employee.setId(id); session.getTransaction().commit(); session.close(); return employee; } ... ... ... // Call the save() method to insert a record in database. System.out.println("******* WRITE *******"); Employee empl = new Employee("Jack", "Bauer", new Date(System.currentTimeMillis()), "911"); empl = save(empl);
Code language: Java (java)

7.2 Reading (Read) data in Hibernate Below code snippet demos read functionality in Hibernate. Note that there are two methods one to list all the employees and other to read details about just one.
private static List list() { SessionFactory sf = HibernateUtil.getSessionFactory(); Session session = sf.openSession(); List employees = session.createQuery("from Employee").list(); session.close(); return employees; } private static Employee read(Long id) { SessionFactory sf = HibernateUtil.getSessionFactory(); Session session = sf.openSession(); Employee employee = (Employee) session.get(Employee.class, id); session.close(); return employee; }
Code language: Java (java)

7.3 Updating (Update) data in Hibernate Following is the code snippet to update a record in Hibernate.
private static Employee update(Employee employee) { SessionFactory sf = HibernateUtil.getSessionFactory(); Session session = sf.openSession(); session.beginTransaction(); session.merge(employee); session.getTransaction().commit(); session.close(); return employee; }
Code language: Java (java)

7.4 Remove (Delete) data in Hibernate Following is code snippet to remove a record in Hibernate.
private static void delete(Employee employee) { SessionFactory sf = HibernateUtil.getSessionFactory(); Session session = sf.openSession(); session.beginTransaction(); session.delete(employee); session.getTransaction().commit(); session.close(); }
Code language: Java (java)
We have created a file Main.java which will test all these functionality. Following is the complete source code of Main.java. File: /src/main/java/net/viralpatel/hibernate/Main.java
package net.viralpatel.hibernate; import java.sql.Date; import java.util.List; import org.hibernate.Session; import org.hibernate.SessionFactory; public class Main { public static void main(String[] args) { // Read System.out.println("******* READ *******"); List employees = list(); System.out.println("Total Employees: " + employees.size()); // Write System.out.println("******* WRITE *******"); Employee empl = new Employee("Jack", "Bauer", new Date(System.currentTimeMillis()), "911"); empl = save(empl); empl = read(empl.getId()); System.out.printf("%d %s %s \n", empl.getId(), empl.getFirstname(), empl.getLastname()); // Update System.out.println("******* UPDATE *******"); Employee empl2 = read(1l); // read employee with id 1 System.out.println("Name Before Update:" + empl2.getFirstname()); empl2.setFirstname("James"); update(empl2); // save the updated employee details empl2 = read(1l); // read again employee with id 1 System.out.println("Name Aftere Update:" + empl2.getFirstname()); // Delete System.out.println("******* DELETE *******"); delete(empl); Employee empl3 = read(empl.getId()); System.out.println("Object:" + empl3); } private static List list() { SessionFactory sf = HibernateUtil.getSessionFactory(); Session session = sf.openSession(); List employees = session.createQuery("from Employee").list(); session.close(); return employees; } private static Employee read(Long id) { SessionFactory sf = HibernateUtil.getSessionFactory(); Session session = sf.openSession(); Employee employee = (Employee) session.get(Employee.class, id); session.close(); return employee; } private static Employee save(Employee employee) { SessionFactory sf = HibernateUtil.getSessionFactory(); Session session = sf.openSession(); session.beginTransaction(); Long id = (Long) session.save(employee); employee.setId(id); session.getTransaction().commit(); session.close(); return employee; } private static Employee update(Employee employee) { SessionFactory sf = HibernateUtil.getSessionFactory(); Session session = sf.openSession(); session.beginTransaction(); session.merge(employee); session.getTransaction().commit(); session.close(); return employee; } private static void delete(Employee employee) { SessionFactory sf = HibernateUtil.getSessionFactory(); Session session = sf.openSession(); session.beginTransaction(); session.delete(employee); session.getTransaction().commit(); session.close(); } }
Code language: Java (java)

8. Final project structure

Once you have created all these source files, your project structure should look like following. Note that we have removed the default App.java and AppTest.java generated by Maven as we dont these files.

9. Execute project

Execute the Main.java class and see output.
******* READ ******* Total Employees: 200 ******* WRITE ******* 201 Jack Bauer ******* UPDATE ******* Name Before Update:Paula Name Aftere Update:James ******* DELETE ******* Object:null
Code language: HTML, XML (xml)

That’s All Folks

Today we saw how to write our first Hibernate hello world example using XML Configuration. We used Maven to generate Java project and added Hibernate dependencies into it. Also we saw how to do different CRUD operations in Hibernate.

Download Source

HibernateHelloWorldXML.zip (8 kb)

View Comments

    • Hi Tom, check if your maven dependencies are properly resolved. It seems that hibernate jar file is not resolved.

    • hi TOm,
      I doing same u, but I cannot run project.
      help me check it, thanks
      error:
      May 07, 2014 3:22:12 PM org.hibernate.cfg.Environment
      INFO: Hibernate 3.2.3
      May 07, 2014 3:22:12 PM org.hibernate.cfg.Environment
      INFO: hibernate.properties not found
      May 07, 2014 3:22:12 PM org.hibernate.cfg.Environment buildBytecodeProvider
      INFO: Bytecode provider name : cglib
      May 07, 2014 3:22:12 PM org.hibernate.cfg.Environment
      INFO: using JDK 1.4 java.sql.Timestamp handling
      May 07, 2014 3:22:12 PM org.hibernate.cfg.Configuration configure
      INFO: configuring from resource: /hibernate.cfg.xml
      May 07, 2014 3:22:12 PM org.hibernate.cfg.Configuration getConfigurationInputStream
      INFO: Configuration resource: /hibernate.cfg.xml
      Exception in thread "main" org.hibernate.HibernateException: /hibernate.cfg.xml not found
      at org.hibernate.util.ConfigHelper.getResourceAsStream(ConfigHelper.java:147)
      at org.hibernate.cfg.Configuration.getConfigurationInputStream(Configuration.java:1405)
      at org.hibernate.cfg.Configuration.configure(Configuration.java:1427)
      at org.hibernate.cfg.Configuration.configure(Configuration.java:1414)
      at net.example.App.main(App.java:18)

  • Hi Viral

    Seems I resolved the maven dependencies but im now getting the following errors:

    - The method setFirstname(String) is undefined for the type Employee
    - The method openSession() is undefined for the type SessionFactory
    - The method setId(Long) is undefined for the type Employee

    • Hi Tom I also faced this problem. Just need to see hibernate.cfg.xml & Employee.hbm.xml file. it should be configured properly. I just correct this one & working fine

  • Hi Viral thanks for this tutorial. I got the output . I am not using Mavan. its just a simple read,Update, & delete Data from database.

  • Okay got this working now - Don't think I had the correct path set for the M2_REPO it should be ~/.M2 for linux but now i'm getting a Null Pointer exception on the delete function.

    Total Employees: 1
    ******* WRITE *******
    607 Jack Bauer
    ******* UPDATE *******
    Exception in thread "main" java.lang.NullPointerException
    at net.viralpatel.hibernate.Main.main(Main.java:33)

    • I think the reason you're getting this exception is that the auto-increment property for the SQL at the top of the tutorial is set as 606 (hence when the record is created, a value of 607 is assigned for the 'ID' as opposed to 1). Try re-creating the table with an auto-increment value of 0 for the 'create table' statement instead.

  • I am Getting below error:

    : org.apache.maven.archetype.old.ArchetypeTemplateProcessingException: Una
    t as it is not of packaging type 'pom'
    Unable to add module to the current project as it is not of packaging type 'pom'

  • hello.......i prepared a simple java project using eclipse hibernate nd it was successfully run on eclipse but i want to see output on command form. using mysql database then which command i use ?????????????

  • This tutorial has a slight mistake.
    Employee.hbm.xml is placed in package net.viralpate.hibernate which is wrong.
    This Employee.hbm.xml must be placed in the src/main/resources folder.

Recent Posts

  • Java

Java URL Encoder/Decoder Example

Java URL Encoder/Decoder Example - In this tutorial we will see how to URL encode/decode…

4 years ago
  • General

How to Show Multiple Examples in OpenAPI Spec

Show Multiple Examples in OpenAPI - OpenAPI (aka Swagger) Specifications has become a defecto standard…

4 years ago
  • General

How to Run Local WordPress using Docker

Local WordPress using Docker - Running a local WordPress development environment is crucial for testing…

4 years ago
  • Java

Create and Validate JWT Token in Java using JJWT

1. JWT Token Overview JSON Web Token (JWT) is an open standard defines a compact…

4 years ago
  • Spring Boot

Spring Boot GraphQL Subscription Realtime API

GraphQL Subscription provides a great way of building real-time API. In this tutorial we will…

4 years ago
  • Spring Boot

Spring Boot DynamoDB Integration Test using Testcontainers

1. Overview Spring Boot Webflux DynamoDB Integration tests - In this tutorial we will see…

5 years ago