Hiberanate 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

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

本文介绍了MySQL的“无法打开共享库”错误。 该问题源于MySQL无法找到必要的共享库(.SO/.DLL文件)。解决方案涉及通过系统软件包M验证库安装

本文探讨了Docker中的优化MySQL内存使用量。 它讨论了监视技术(Docker统计,性能架构,外部工具)和配置策略。 其中包括Docker内存限制,交换和cgroups

本文讨论了使用MySQL的Alter Table语句修改表,包括添加/删除列,重命名表/列以及更改列数据类型。

本文比较使用/不使用PhpMyAdmin的Podman容器直接在Linux上安装MySQL。 它详细介绍了每种方法的安装步骤,强调了Podman在孤立,可移植性和可重复性方面的优势,还

本文提供了SQLite的全面概述,SQLite是一个独立的,无服务器的关系数据库。 它详细介绍了SQLite的优势(简单,可移植性,易用性)和缺点(并发限制,可伸缩性挑战)。 c

文章讨论了为MySQL配置SSL/TLS加密,包括证书生成和验证。主要问题是使用自签名证书的安全含义。[角色计数:159]

本指南展示了使用自制在MacOS上安装和管理多个MySQL版本。 它强调使用自制装置隔离安装,以防止冲突。 本文详细详细介绍了安装,起始/停止服务和最佳PRA

文章讨论了流行的MySQL GUI工具,例如MySQL Workbench和PhpMyAdmin,比较了它们对初学者和高级用户的功能和适合性。[159个字符]
