欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  数据库

Hiberanate 4 Tutorial using Maven and MySQL_MySQL

程序员文章站 2022-06-07 14:06:57
...
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.

4.0.0com.javahash.hibernateHibernateTutorial0.0.1-SNAPSHOTjarHibernateTutorialhttp://maven.apache.orgUTF-8junitjunit3.8.1testorg.hibernatehibernate-core4.3.5.Finalmysqlmysql-connector-java5.1.6

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.

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.

org.hibernate.dialect.MySQLDialectcom.mysql.jdbc.Driverjdbc:mysql://localhost:3306/testUSERPASSWORDtrue

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