ホームページ > データベース > mysql チュートリアル > Hiberanate 4 Tutorial using Maven and MySQL_MySQL

Hiberanate 4 Tutorial using Maven and MySQL_MySQL

WBOY
リリース: 2016-06-01 13:14:37
オリジナル
1383 人が閲覧しました

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

ソース:php.cn
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート