Web开发:Struts2 Spring Hibernate整合(三)上——Hibernate的使用

    前面并没有使用数据库,这里使用mysql数据库,在前面的基础上使用hibernate,首先可以先试试hibernate单独怎么使用。

Hibernate的单独使用:

(1)首先导入Hibernate的包:

<!-- 添加Hibernate依赖 -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>3.6.5.Final</version>
        </dependency>
<!-- MySQL database driver -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.9</version>
        </dependency>

 (2)配置Hibernate配置文件:创建hibernate.cfg.xml,内容如下,主要是告诉Hibernate怎么连数据库,Hibernate采用关系对象映射,所以需要配置关系映射表,在mapping中:

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

<hibernate-configuration>
    <session-factory >

        <!-- local connection properties -->
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/example</property>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.username">mzuser</property>
        <property name="hibernate.connection.password">123456</property>
        <!-- property name="hibernate.connection.pool_size"></property -->

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

        <property name="hibernate.show_sql">true</property>
        <property name="hibernate.transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
        <mapping resource="com/mz/bean/UserBean.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

 (3)创建UserBean类(实例化对象对应数据库里的关系,即表)

package com.mz.bean;

/**
 * Created by hadoop on 15-9-9.
 */
public class UserBean {
    private int userid;
    private String username;
    private String password;
    private String area;
    private String deptrole;

    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 getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getArea() {
        return area;
    }

    public void setArea(String area) {
        this.area = area;
    }

    public String getDeptrole() {
        return deptrole;
    }

    public void setDeptrole(String deptrole) {
        this.deptrole = deptrole;
    }
}

 (4)关系映射表:创建UserBean.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 package="com.mz.bean">
    <class name="UserBean" table="CmsUser">
        <id name="userid" type="int">
            <column name="userid"></column>
            <generator class="increment"/>
        </id>
        <property name="username" type="java.lang.String">
            <column name="username" length="20"></column>
        </property>
        <property name="password" type="java.lang.String">
            <column name="password" length="20"></column>
        </property>
        <property name="area" type="java.lang.String">
            <column name="area" length="10"></column>
        </property>
        <property name="deptrole" type="java.lang.String">
            <column name="deptrole" length="10"></column>
        </property>
    </class>

</hibernate-mapping>

 (5)接下来就是创建数据库,在数据库中建立以下表:

+----------+-------------+------+-----+---------+----------------+
| Field    | Type        | Null | Key | Default | Extra          |
+----------+-------------+------+-----+---------+----------------+
| userid   | int(8)      | NO   | PRI | NULL    | auto_increment |
| username | varchar(20) | NO   |     | NULL    |                |
| password | varchar(20) | YES  |     | NULL    |                |
| area     | varchar(10) | YES  |     | NULL    |                |
| deptrole | varchar(10) | YES  |     | NULL    |                |
+----------+-------------+------+-----+---------+----------------+

 (6)测试:首先创建SessionFactory工具类,Hibernate创建连接:

package com.mz.utils;

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

/**
 * Created by hadoop on 15-9-9.
 */
public class SessionUtil {
    private static final ThreadLocal<Session> sm = new ThreadLocal<Session>();
    private static final SessionFactory sessionFactory;

    static {
        sessionFactory = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();
    }

    public static Session getSession(){
        Session session = sm.get();
        if(session == null) {
            session = sessionFactory.openSession();
            sm.set(session);
        }
        return session;
    }

    public static void closeSession(){
        Session session = sm.get();
        sm.set(null);
        if(session != null){
            session.close();
        }
    }
}

 测试类:

package com.mz.bean;

import com.mz.utils.SessionUtil;
import org.hibernate.Session;
import org.junit.Test;

/**
 * Created by hadoop on 15-9-9.
 */
public class UserBeanTest {

    @Test
    public void testHibernateSession(){
        SessionUtil.getSession();
        SessionUtil.closeSession();
    }

    @Test
    public void testUserBean(){
        Session session = SessionUtil.getSession();
        org.hibernate.Transaction transaction = session.beginTransaction();
        UserBean userBean = new UserBean();
        userBean.setUsername("mzuser");
        userBean.setPassword("123456");
        userBean.setArea("北京");
        userBean.setDeptrole("销售");
        session.save(userBean);
        transaction.commit();
        SessionUtil.closeSession();
    }

}

 执行测试类,查询数据库,能够成功插入数据。

 相关内容

(1)Web开发:Struts2 Spring Hibernate整合(一)——Struts2的使用

(2)Web开发:Struts2 Spring Hibernate整合(二)——Spring的使用

(3)Web开发:Struts2 Spring Hibernate整合(三)下——Hibernate的使用

相关推荐