Create a simple Hibernate example with Maven and Eclipse
In this tutorial, we will discuss how to integrate Hibernate, Maven and MYSQL. After completing this tutorial you will learn how to work with Hibernate and insert a record into MySQL database using Hibernate framework.
Tools used :
- Maven 3.0.5
- Hibernate 4
- Eclipse Indigo
- JDK 6
- Mysql 5.1
Table Creation
CREATE TABLE USER ( USER_ID INT (5) NOT NULL, USERNAME VARCHAR (20) NOT NULL, CREATED_BY VARCHAR (20) NOT NULL, CREATED_DATE DATE NOT NULL, PRIMARY KEY ( USER_ID ) )
In this tutorial, we will discuss how to integrate Hibernate, Maven and MYSQL. After completing this tutorial you will learn how to work with Hibernate and insert a record into MySQL database using Hibernate framework.
Tools used :
- Maven 3.0.5
- Hibernate 4
- Eclipse Indigo
- JDK 6
- Mysql 5.1
Table Creation
CREATE TABLE USER ( USER_ID INT (5) NOT NULL, USERNAME VARCHAR (20) NOT NULL, CREATED_BY VARCHAR (20) NOT NULL, CREATED_DATE DATE NOT NULL, PRIMARY KEY ( USER_ID ) )
Create a java Project using Maven tool
In the command prompt execute the following command to generate Maven compatible Java project named as 'HibernateSampleExample'.
mvn archetype:generate -DgroupId=com.javawebtutor -DartifactId=HibernateSampleExample -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
This command tell Maven to create a Java project from “maven-archetype-quickstart” template. If you ignore the archetypeArtifactId argument, a list of the templates will be listed for you to choose.
This command creates a new Java project under the name HibernateSampleExample, along with its entire directory structure.
Convert to eclipse project
To convert Maven project to support Eclipse IDE, in terminal, navigate to “HibernateSampleExample” project, and issue mvn eclipse:eclipse command .
Import converted project into Eclipse IDE
In Eclipse IDE, Choose File –> Import –> General -> Existing Projects into Workspace –>Choose your project folder location. Done
Create a resources folder
Create a resources folder under "src/main" folder, “/src/main/resources” , We will put all Hibernate’s xml files here. Maven will treat all files in this folder as resources files, and copy it to class path automatically.
Directory Structure of Project
Add hibernate dependency in pom.xml
Once your Maven base project has been created using Eclipse, Define the below hibernate,mysql and other dependencies in pom.xml file.
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>com.javawebtutor</groupId> <artifactId>HibernateSampleExample</artifactId> <packaging>jar</packaging> <version>1.0-SNAPSHOT</version> <name>HibernateSampleExample</name> <url>http://maven.apache.org</url> <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> </project>
Issue the “mvn eclipse:eclipse“, Maven will download all Hibernate and MySQL libraries automatically and put into Maven’s local repository. At the same time, Maven will add the downloaded libraries into Eclipse “.classpath” for dependency purpose.
Add hibernate configuration xml(hibernate.cfg.xml)
Now our project setup is ready.We need to create "hibernate.cfg.xml" file in "/src/main/resources" folder. Create a xml file inside "/src/main/resources" name it to "hibernate.cfg.xml" and add following code into this file
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/javawebtutor</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">mukesh</property> <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> <mapping resource="user.hbm.xml" /> </session-factory> </hibernate-configuration>
Create model class (Pojo Class)
Craete a java class User in the package com.javawebtutor and add following code in this class.
package com.javawebtutor; import java.util.Date; public class User { private int userId; private String username; private String createdBy; private Date createdDate; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } 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; } public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } }
Mapping for model class
Create "user.hbm.xml" mapping file in the folder "src/main/resources"and add following code to map model class to database table column.
<?xmlversion="1.0"?> <!DOCTYPEhibernate-mappingPUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="com.javawebtutor.User"table="USER"> <id name="userId"type="int"column="USER_ID"> <generator class="assigned"/> </id> <property name="username"> <column name="USERNAME"/> </property> <property name="createdBy"> <column name="CREATED_BY"/> </property> <property name="createdDate"type="date"> <column name="CREATED_DATE"/> </property> </class> </hibernate-mapping>
Create hibernate utility class
Create a HibernateUtil.java class to take care of Hibernate start up and retrieve the session easily.
package com.javawebtutor; 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) { // Make sure you log the exception, as it might be swallowed 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(); } }
Test Program
Create Test class to insert data into DB.
package com.javawebtutor; import java.util.Date; import org.hibernate.Session; public class Test { public static void main(String[] args) { Session session = HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); User user = new User(); user.setUserId(1); user.setUsername("Mukesh"); user.setCreatedBy("Google"); user.setCreatedDate(new Date()); session.save(user); session.getTransaction().commit(); } }
Output
Run the Test class you will see following output in console.
Hibernate: insert into USER (USERNAME, CREATED_BY, CREATED_DATE, USER_ID) values (?, ?, ?, ?)
Check the Table you can see following data in table
mysql> select * from user; +---------+----------+------------+--------------+ | USER_ID | USERNAME | CREATED_BY | CREATED_DATE | +---------+----------+------------+--------------+ | 1 | Mukesh | Google | 2014-06-13 | +---------+----------+------------+--------------+ 1 row in set (0.00 sec)
You can download the source code of the example by clicking on the Download link below.
Source : Download |
Source + Lib : Download |