Hibernate+maven+mysql

最近在研究hibernate,想建立一个简单的Hibernate+maven+mysql工程,网上找了一大堆的示例,要么看不懂结构,要么就是缺少必要文件。总之都没有成功,结果无意在一个外文网上找了一个实例,惊叹于人家的排版。也不得不感叹的说下浩瀚的百度里,想找到自己想要的东西是多么难啊!

以下借鉴人家文章和内容并做部分补充,以供初学者一起分享:

(准备工作myeclipse的安装+maven的下载+mysql的配置略过)

 

1.mysql中建一个mkyong的数据库,其下面新建一个stock的空表格。

   //启动mysql服务器
   sudo service mysql start
   //进入mysql
   mysql -uroot -p
   输入mysql密码
   //创建数据库mkyong
   >create database mkyong;
   //使用数据库mkyong
   >use mkyong;
  //在数据库mkyong中创建表stock。请直接copy。
  >create table stock (
            `STOCK_ID` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
            `STOCK_CODE` VARCHAR(10) NOT NULL,
            `STOCK_NAME` VARCHAR(20) NOT NULL,
            PRIMARY KEY (`STOCK_ID`) USING BTREE,
            UNIQUE KEY `UNI_STOCK_NAME` (`STOCK_NAME`),
            UNIQUE KEY `UNI_STOCK_ID` (`STOCK_CODE`) USING BTREE
         ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

 

2.在myeclipse中创建一个maven工程,自己取一个名字。

New --> Project --> Maven Project --> Next --> 在(New Maven Project )中选择创建一个webapp项目

 

3.创建源文件(Source Folder)

在 “src/main”目录下创建 “/src/main/resources” , 之后所有的Hibernate’s xml配置文件都将放置在该文件下。

在“src/main”目录下创建“/src/main/java”文件,其中放置java源代码文件。

 

4.现在该工程的结构看起来如下:

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

5.添加Hibernate和Mysql依赖

修改项目的pom.xml配置文件,它将支持Hibernate和mysql的连接,Hibernate项目需要dom4j, commons-logging, commons-collections和 cglib文件,mysql需要连接jdbc的文件。将原来的内容更换为如下代码。

文件:pom.xml

<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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com</groupId>
  <artifactId>Hibernate</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>Hibernate Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
        <!-- MySQL database driver -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.9</version>
    </dependency>
    <!-- Hibernate library dependecy start -->
    <dependency>
        <groupId>dom4j</groupId>
        <artifactId>dom4j</artifactId>
        <version>1.6.1</version>
    </dependency> 
    <dependency>
        <groupId>commons-logging</groupId>
        <artifactId>commons-logging</artifactId>
        <version>1.1.1</version>
    </dependency>
    <!-- http://mvnrepository.com/artifact/org.hibernate/hibernate -->
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate</artifactId>
        <version>3.2.6.ga</version>
    </dependency>
    <dependency>
        <groupId>commons-collections</groupId>
        <artifactId>commons-collections</artifactId>
        <version>3.2.1</version>
    </dependency>
    <dependency>
        <groupId>cglib</groupId>
        <artifactId>cglib-nodep</artifactId>
        <version>3.1</version>
    </dependency>
    <!-- Hibernate library dependecy end -->
    <dependency>
        <groupId>javax.transaction</groupId>
        <artifactId>jta</artifactId>
        <version>1.1</version>
    </dependency>  
  </dependencies>
  <build>
    <finalName>Hibernate</finalName>
  </build>
</project>

 

6.创建Hibernate类表映射文件

新建一个Stock.hbm.xml映射文件,路径为:“src/main/resources/com/mkyong/common/Stock.hbm.xml

文件:Stock.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
    <class name="com.mkyong.common.Stock" table="stock" catalog="mkyong">
        <id name="stockId" type="java.lang.Integer">
            <column name="STOCK_ID" />
            <generator class="identity" />
        </id>
        <property name="stockCode" type="string">
            <column name="STOCK_CODE" length="10" not-null="true" unique="true" />
        </property>
        <property name="stockName" type="string">
            <column name="STOCK_NAME" length="20" not-null="true" unique="true" />
        </property>
    </class>
</hibernate-mapping>

 

7.创建一个Stock的POJO  java文件,路径为:“src/main/java/com/mkyong/common/Stock.java

文件:Stock.java

package com.mkyong.common;

/**
 * Model class for Stock
 */
public class Stock implements java.io.Serializable {

    private static final long serialVersionUID = 1L;
    private Stock stock;
    private Integer stockId;
    private String stockCode;
    private String stockName;

    public Stock() {
    }

    public Stock(String stockCode, String stockName) {
        this.stockCode = stockCode;
        this.stockName = stockName;
    }

    public Integer getStockId() {
        return this.stockId;
    }

    public void setStockId(Integer stockId) {
        this.stockId = stockId;
    }

    public String getStockCode() {
        return this.stockCode;
    }

    public void setStockCode(String stockCode) {
        this.stockCode = stockCode;
    }

    public String getStockName() {
        return this.stockName;
    }

    public void setStockName(String stockName) {
        this.stockName = stockName;
    }
    public Stock getOper() {
        return stock;
    }
 
    public void setOper(Stock stock) {
        this.stock = stock;
    }
}

 

 

8.创建Hibernate配置文件

创建一个Hibernate配置文件,路径为:“src/main/resources/hibernate.cfg.xml“。(注意修改其中的“数据库密码”,mkyong即为数据库的名称)

文件:hibernate.cfg.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.bytecode.use_reflection_optimizer">false</property>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.password">数据库的密码</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/mkyong</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="person">true</property>
        <mapping resource="com/mkyong/common/Stock.hbm.xml"></mapping>
    </session-factory>
</hibernate-configuration>

 

 

9.创建Hibernate会话文件

创建一个java类型的Hibernate会话文件,路径为:“src/main/java/com/mkyong/persistence/HibernateUtil.java”。
文件:HibernateUtil.java

 

package com.mkyong.persistence;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {

    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("Initial 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();
    }
}

 

 

10.创建测试文件

创建一个名为App.java的测试文件,路径为:“src/main/java/com/mkyong/common/App.java”.

文件:App.java

package com.mkyong.common;

import org.hibernate.Session;
import com.mkyong.persistence.HibernateUtil;

public class App 
{
    public static void main( String[] args )
    {
        System.out.println("Maven + Hibernate + MySQL");
        Session session = HibernateUtil.getSessionFactory().openSession();
        
        session.beginTransaction();
        Stock stock = new Stock();
        
        stock.setStockCode("4715");
        stock.setStockName("GENM");
        
        session.save(stock);
        session.getTransaction().commit();
    }
}

 

 

11.再来看看工程的结构

创建和修改的六个文件结构如下:

 

12.运行结果

运行App.java这个程序,它将会插入一条数据到mysql数据库中去。我们可以在myeclipse中看到该结果,也可以去mysql数据库中查看是否已经插入成功。以下是运行结果:

Picked up _JAVA_OPTIONS:   -Dawt.useSystemAAFontSettings=gasp
Maven + Hibernate + MySQL
.......
五月 24, 2016 5:31:56 上午 org.hibernate.impl.SessionFactoryImpl <init>
信息: building session factory
五月 24, 2016 5:31:56 上午 org.hibernate.impl.SessionFactoryObjectFactory addInstance
信息: Hibernate: insert into mkyong.stock (STOCK_CODE, STOCK_NAME) values (?, ?)

 

 

 参考文件链接:Maven+Hibernate+Mysql Example(XML Mapping)

     源文件下载:Maven+Hibernate+Mysql Example(XML Mapping)

 

posted @ 2016-05-24 13:45  Hosens  阅读(6053)  评论(4编辑  收藏  举报