日期:2014-05-16  浏览次数:20807 次

用Jersey构建RESTful服务5--Jersey+MySQL5.6+Hibernate4.3

一、总体说明

本例运行演示了用Jersey构建RESTful服务中,如何同过Hibernate将数据持久化进MySQL的过程

二、环境

1.上文的项目RestDemo

2.MySQL5.6下载http://dev.mysql.com/get/Downloads/MySQL-5.6/mysql-5.6.16-win32.zip

3.Hibernate4.3.4下载http://sourceforge.net/projects/hibernate/files/hibernate4/4.3.4.Final/hibernate-release-4.3.4.Final.zip

4.Java程序连接MySQL的驱动mysql-connector-java-5.1.29-bin.jar下载
http://dev.mysql.com/get/Downloads/Connector-J/mysql-connector-java-5.1.29.zip

三、数据库准备

1.搭建MySQL数据库

2.创建数据库RestDemo ,及数据表t_user,结构如下

DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user` (
  `userId` varchar(50) NOT NULL,
  `userName` varchar(50) NOT NULL,
  `age` varchar(50) NOT NULL,
  PRIMARY KEY (`userId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


ps:   userId 非自增长类型,需要在业务添加

四、引入Hibernate

1.解压Hibernate的包,在lib\required文件夹下所有jar引入进项目


2.解压mysql-connector-java-5.1.29.zip,将mysql-connector-java-5.1.29-bin.jar引入进项目

3.在项目的根目录创建hibernate的配置文件hibernate.cfg.xml,内容如下:

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
   <session-factory>
   <!-- Database connection settings -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://127.0.0.1:3306/RestDemo</property>
        <property name="connection.username">root</property>
        <property name="connection.password"></property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
 
        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>

        <!-- Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">update</property>


        <mapping resource="com/waylau/rest/bean/User.hbm.xml"/>
 
    </session-factory>
</hibernate-configuration>

4.在项目User.java 的同个目录下,创建该类的映射文件User.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

 
<hibernate-mapping package="com.waylau.rest.bean">

    <class name="User" table="T_USER">
        <id name="userId" column="USERID"  type="string" >
            <generator class="assigned"/>