> 데이터 베이스 > MySQL 튜토리얼 > Hiberanate 4 Tutorial using Maven and MySQL_MySQL

Hiberanate 4 Tutorial using Maven and MySQL_MySQL

WBOY
풀어 주다: 2016-06-01 13:14:37
원래의
1394명이 탐색했습니다.

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으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿