search
HomeDatabaseMysql TutorialHiberanate 4 Tutorial using Maven and MySQL_MySQL

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

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Reduce the use of MySQL memory in DockerReduce the use of MySQL memory in DockerMar 04, 2025 pm 03:52 PM

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

How to solve the problem of mysql cannot open shared libraryHow to solve the problem of mysql cannot open shared libraryMar 04, 2025 pm 04:01 PM

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

How do you alter a table in MySQL using the ALTER TABLE statement?How do you alter a table in MySQL using the ALTER TABLE statement?Mar 19, 2025 pm 03:51 PM

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

Run MySQl in Linux (with/without podman container with phpmyadmin)Run MySQl in Linux (with/without podman container with phpmyadmin)Mar 04, 2025 pm 03:54 PM

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

What is SQLite? Comprehensive overviewWhat is SQLite? Comprehensive overviewMar 04, 2025 pm 03:55 PM

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

How do I configure SSL/TLS encryption for MySQL connections?How do I configure SSL/TLS encryption for MySQL connections?Mar 18, 2025 pm 12:01 PM

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]

Running multiple MySQL versions on MacOS: A step-by-step guideRunning multiple MySQL versions on MacOS: A step-by-step guideMar 04, 2025 pm 03:49 PM

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

What are some popular MySQL GUI tools (e.g., MySQL Workbench, phpMyAdmin)?What are some popular MySQL GUI tools (e.g., MySQL Workbench, phpMyAdmin)?Mar 21, 2025 pm 06:28 PM

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

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

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 new version

SublimeText3 Linux latest version

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)