In this tutorial, I will show you how to integrate Hibernate 4.X , 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
Table
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 ))
Maven
You can use Maven to create the project structure.
mvn archetype:generate -DgroupId=com.javahash -DartifactId=HibernateTutorial -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
This will create a maven project with all necessary folders. This project needs to be converted to an eclipse project, as we are using Eclipse as the IDE for this tutorial. This can be accomplished using the command.
mvn eclipse:eclipse
You can import the project to eclipse using the File -> Import option.
Managing Dependency
Complete pom.xml is shown below. Do notice the dependencies added for Hibernate and MySQL connector.
<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/xsd/maven-4.0.0.xsd"> <modelversion>4.0.0</modelversion><groupid>com.javahash.hibernate</groupid> <artifactid>HibernateTutorial</artifactid> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging><name>HibernateTutorial</name> <url>http://maven.apache.org</url><properties> <project.build.sourceencoding>UTF-8</project.build.sourceencoding> </properties><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>
Model
Next step is to create the Java class modelling the user table and define the hibernate configuration to map the java class to table columns.
User
package com.javahash.hibernate;import java.io.Serializable;import java.util.Date;public class User implements Serializable{private int userId; private String username; private String createdBy; private Date createdDate; public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } 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; }}
Mapping for User
User.hbm.xml
I have created the User.hbm.xml mapping file in the foldersrc/main/resources. If the folder doesn’t exist in your project, you can create one.
<?xml version="1.0"?><hibernate-mapping> <class name="com.javahash.hibernate.User" table="USER"> <id name="userId" type="int" column="USER_ID"> <generator class="assigned"></generator> </id> <property name="username"> <column name="USERNAME"></column> </property> <property name="createdBy"> <column name="CREATED_BY"></column> </property> <property name="createdDate" type="date"> <column name="CREATED_DATE"></column> </property> </class></hibernate-mapping>
Hibernate Session Configuration
In this step we will configure the things needed for Hibernate to establish connection to the database we use, MySQL in this case. For this create a file namedhibernate.cfg.xml in the root package. That is inside the srcfolder.
<?xml version="1.0" encoding="utf-8"?><hibernate-configuration> <session-factory> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property> <property name="hibernate.connection.username">USER</property> <property name="hibernate.connection.password">PASSWORD</property> <property name="show_sql">true</property> <mapping resource="User.hbm.xml"></mapping></session-factory></hibernate-configuration>
Now we have told hibernate enough information about the database we use and how to connect to it. When you work with Hibernate, the process is to get a Hibernate Session and use the session to interact with the database. We need a class that holds initializes and holds the Session Factory. For this, we create Class named HibernateSessionManager and expose static method to get the session.
HibernateSessionManager.java
package com.javahash.hibernate;import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;public class HibernateSessionManager { 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(); }}
The Client
All our configurations are done. We are now left with the task of writing a client that saves the user to the database.
package com.javahash.hibernate;import java.util.Date;import org.hibernate.Session;public class Run {/** * @param args */ public static void main(String[] args) { Session session = HibernateSessionManager.getSessionFactory().openSession(); session.beginTransaction(); User user = new User(); user.setUserId(1); user.setUsername("James"); user.setCreatedBy("Application"); user.setCreatedDate(new Date()); session.save(user); session.getTransaction().commit();}}
If the programs runs fine you should see the following query in the console
Hibernate: insert into USER (USERNAME, CREATED_BY, CREATED_DATE, USER_ID) values (?, ?, ?, ?)
Remember we have put show_sqlas true in hibernate.cfg.xml. Hope you find this tutorial useful.
Download Source Code
Download Project Source Code

This article explores optimizing MySQL memory usage in Docker. It discusses monitoring techniques (Docker stats, Performance Schema, external tools) and configuration strategies. These include Docker memory limits, swapping, and cgroups, alongside

This article addresses MySQL's "unable to open shared library" error. The issue stems from MySQL's inability to locate necessary shared libraries (.so/.dll files). Solutions involve verifying library installation via the system's package m

The article discusses using MySQL's ALTER TABLE statement to modify tables, including adding/dropping columns, renaming tables/columns, and changing column data types.

This article compares installing MySQL on Linux directly versus using Podman containers, with/without phpMyAdmin. It details installation steps for each method, emphasizing Podman's advantages in isolation, portability, and reproducibility, but also

This article provides a comprehensive overview of SQLite, a self-contained, serverless relational database. It details SQLite's advantages (simplicity, portability, ease of use) and disadvantages (concurrency limitations, scalability challenges). C

Article discusses configuring SSL/TLS encryption for MySQL, including certificate generation and verification. Main issue is using self-signed certificates' security implications.[Character count: 159]

This guide demonstrates installing and managing multiple MySQL versions on macOS using Homebrew. It emphasizes using Homebrew to isolate installations, preventing conflicts. The article details installation, starting/stopping services, and best pra

Article discusses popular MySQL GUI tools like MySQL Workbench and phpMyAdmin, comparing their features and suitability for beginners and advanced users.[159 characters]


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version
SublimeText3 Linux latest version

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Atom editor mac version download
The most popular open source editor

SublimeText3 Mac version
God-level code editing software (SublimeText3)
