Maven搭建Hibernate4開發環境並整合Spring3

前面整合maven和spring3,struts2,這篇整合hibernate。
1.下載Hibernate4需要的jar包
在pom.xml文件中編寫Hibernate4所需要的jar包,Maven會自動下載這些包。

<!-- hibernate4 -->
         <dependency>
             <groupId>org.hibernate</groupId>
             <artifactId>hibernate-core</artifactId>
             <version>4.1.7.Final</version>
         </dependency>

這裏寫圖片描述

注意:一定要排除掉Struts2中的javassist,否則就衝突了。
也就是將pom.xml裏配置strust2內取消這段代碼註釋:

<exclusions>
        <exclusion>
          <groupId>javassist</groupId>
           <artifactId>javassist</artifactId>
        </exclusion>
</exclusions> 

2.添加數據庫驅動包
這裏我用的數據庫是mysql

<!-- mysql驅動包 -->
2         <dependency>
3             <groupId>mysql</groupId>
4             <artifactId>mysql-connector-java</artifactId>
5             <version>5.1.34</version>
6         </dependency>

3.添加數據庫連接池jar包
在平時開發中,我們一般都會使用數據庫連接池,應用系統初始化時,由數據庫連接池向數據庫申請一定數量的數據庫連接,然後放到一個連接池中,當需要操作數據庫時,就從數據庫連接池中取出一個數據庫連接,通過從連接池中獲取到的數據庫連接對象連接上數據庫,然後進行CRUD操作,關於數據庫連接池的選擇,常用的有DBCP,C3P0和Druid,這裏我們使用Druid作爲我們的數據庫連接池。

在pom.xml文件中編寫Druid的jar包,Maven會自動下載,如下:

<!--Druid連接池包 -->
         <dependency>
             <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
             <version>1.0.12</version>
         </dependency>

4.添加aspectjweaver包
使用Spring的aop時需要使用到aspectjweaver包,所以需要添加aspectjweaver包,在pom.xml文件中添加aspectjweaver的jar包,Maven會自動下載,如下:

 <!--aspectjweaver包 -->
         <dependency>
             <groupId>org.aspectj</groupId>
             <artifactId>aspectjweaver</artifactId>
             <version>1.8.5</version>
         </dependency>

5、編寫連接數據庫的配置信息
之前我們在src/main/resources目錄下創建了一個config.properties文件,裏面的內容是空的,現在我們就在這個config.properties文件中編寫連接數據庫需要使用到的相關信息,如下所示:

#hibernate.dialect=org.hibernate.dialect.OracleDialect
#driverClassName=oracle.jdbc.driver.OracleDriver
#validationQuery=SELECT 1 FROM DUAL
#jdbc_url=jdbc:oracle:thin:@127.0.0.1:1521:orcl
#jdbc_username=sshe
#jdbc_password=sshe

hibernate.dialect=org.hibernate.dialect.MySQLDialect
driverClassName=com.mysql.jdbc.Driver
validationQuery=SELECT 1
jdbc_url=jdbc:mysql://localhost:3306/ssh?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
jdbc_username=root
jdbc_password=18324

#hibernate.dialect=org.hibernate.dialect.SQLServerDialect
#driverClassName=net.sourceforge.jtds.jdbc.Driver
#validationQuery=SELECT 1
#jdbc_url=jdbc:jtds:sqlserver://127.0.0.1:1433/sy
#jdbc_username=sa
#jdbc_password=123456

#jndiName=java:comp/env/dataSourceName

hibernate.hbm2ddl.auto=update
hibernate.show_sql=true
hibernate.format_sql=true

sessionInfoName=sessionInfo

uploadFieldName=filedata
uploadFileMaxSize=20971520
uploadFileExts=txt,rar,zip,doc,docx,xls,xlsx,jpg,jpeg,gif,png,swf,wmv,avi,wma,mp3,mid
uploadDirectory=attached

這裏的jdbc_url=jdbc:mysql://localhost:3306/ssh?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull代碼,3306後面是數據庫名ssh。

在src/main/resources目錄下新建一個spring-hibernate.xml文件,如下圖所示:

這裏寫圖片描述

內容如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="
http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
http://www.springframework.org/schema/tx 
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop 
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
">

    <!-- JNDI方式配置數據源 -->
    <!-- <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean"> <property name="jndiName" value="${jndiName}"></property> </bean> -->

    <!-- 配置數據源 -->
    <bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <property name="url" value="${jdbc_url}" />
        <property name="username" value="${jdbc_username}" />
        <property name="password" value="${jdbc_password}" />

        <!-- 初始化連接大小 -->
        <property name="initialSize" value="0" />
        <!-- 連接池最大使用連接數量 -->
        <property name="maxActive" value="20" />
        <!-- 連接池最大空閒 -->
        <property name="maxIdle" value="20" />
        <!-- 連接池最小空閒 -->
        <property name="minIdle" value="0" />
        <!-- 獲取連接最大等待時間 -->
        <property name="maxWait" value="60000" />

        <!-- <property name="poolPreparedStatements" value="true" /> <property name="maxPoolPreparedStatementPerConnectionSize" value="33" /> -->

        <property name="validationQuery" value="${validationQuery}" />
        <property name="testOnBorrow" value="false" />
        <property name="testOnReturn" value="false" />
        <property name="testWhileIdle" value="true" />

        <!-- 配置間隔多久才進行一次檢測,檢測需要關閉的空閒連接,單位是毫秒 -->
        <property name="timeBetweenEvictionRunsMillis" value="60000" />
        <!-- 配置一個連接在池中最小生存的時間,單位是毫秒 -->
        <property name="minEvictableIdleTimeMillis" value="25200000" />

        <!-- 打開removeAbandoned功能 -->
        <property name="removeAbandoned" value="true" />
        <!-- 1800秒,也就是30分鐘 -->
        <property name="removeAbandonedTimeout" value="1800" />
        <!-- 關閉abanded連接時輸出錯誤日誌 -->
        <property name="logAbandoned" value="true" />

        <!-- 監控數據庫 -->
        <!-- <property name="filters" value="stat" /> -->
        <property name="filters" value="mergeStat" />
    </bean>

    <!-- 配置hibernate session工廠 -->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
                <prop key="hibernate.dialect">${hibernate.dialect}</prop>
                <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
                <prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
            </props>
        </property>

        <!-- 自動掃描註解方式配置的hibernate類文件 -->
        <property name="packagesToScan">
            <list>
                <value>sy.model</value>
            </list>
        </property>

        <!-- 自動掃描hbm方式配置的hibernate文件和.hbm文件 -->
        <!-- 
        <property name="mappingDirectoryLocations">
            <list>
                <value>classpath:sy/hbm</value>
            </list>
        </property>
         -->
    </bean>

    <!-- 配置事務管理器 -->
    <bean name="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>

    <!-- 註解方式配置事物 -->
    <!-- <tx:annotation-driven transaction-manager="transactionManager" /> -->

    <!-- 攔截器方式配置事物 -->
    <tx:advice id="transactionAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="add*" />
            <tx:method name="save*" />
            <tx:method name="update*" />
            <tx:method name="modify*" />
            <tx:method name="edit*" />
            <tx:method name="delete*" />
            <tx:method name="remove*" />
            <tx:method name="repair" />
            <tx:method name="deleteAndRepair" />

            <tx:method name="get*" propagation="SUPPORTS" />
            <tx:method name="find*" propagation="SUPPORTS" />
            <tx:method name="load*" propagation="SUPPORTS" />
            <tx:method name="search*" propagation="SUPPORTS" />
            <tx:method name="datagrid*" propagation="SUPPORTS" />

            <tx:method name="*" propagation="SUPPORTS" />
        </tx:attributes>
    </tx:advice>
    <aop:config>
        <aop:pointcut id="transactionPointcut" expression="execution(* sy.service..*Impl.*(..))" />
        <aop:advisor pointcut-ref="transactionPointcut" advice-ref="transactionAdvice" />
    </aop:config>


</beans>

7、編寫單元測試代碼
1、在MySQL中創建ssh數據庫

  SQL腳本:

CREATE DATABASE ssh;

2.在src/main/java中創建sy.model包,在包中編寫一個 Tuer類,如下圖所示:
這裏寫圖片描述

Tuser內容:

package sy.model;

import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.UniqueConstraint;

/**
 * Tuser entity. @author MyEclipse Persistence Tools
 */
@Entity
@Table(name = "TUSER", schema = "ssh", uniqueConstraints = @UniqueConstraint(columnNames = "NAME"))
public class Tuser implements java.io.Serializable {

    // Fields

    private String id;
    private String name;
    private String pwd;
    private Date createdatetime;
    private Date modifydatetime;

    // Constructors

    /** default constructor */
    public Tuser() {
    }

    /** minimal constructor */
    public Tuser(String id, String name, String pwd) {
        this.id = id;
        this.name = name;
        this.pwd = pwd;
    }

    /** full constructor */
    public Tuser(String id, String name, String pwd, Date createdatetime, Date modifydatetime) {
        this.id = id;
        this.name = name;
        this.pwd = pwd;
        this.createdatetime = createdatetime;
        this.modifydatetime = modifydatetime;
    }

    // Property accessors
    @Id
    @Column(name = "ID", unique = true, nullable = false, length = 36)
    public String getId() {
        return this.id;
    }

    public void setId(String id) {
        this.id = id;
    }

    @Column(name = "NAME", unique = true, nullable = false, length = 100)
    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Column(name = "PWD",length = 32)
    public String getPwd() {
        return this.pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "CREATEDATETIME", length = 7)
    public Date getCreatedatetime() {
        return this.createdatetime;
    }

    public void setCreatedatetime(Date createdatetime) {
        this.createdatetime = createdatetime;
    }

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "MODIFYDATETIME", length = 7)
    public Date getModifydatetime() {
        return this.modifydatetime;
    }

    public void setModifydatetime(Date modifydatetime) {
        this.modifydatetime = modifydatetime;
    }

}

3、在src/main/java中創建sy.dao包,在包中編寫一個 UserDaoI接口,如下圖所示:
代碼如下:

package sy.dao;

import java.io.Serializable;

import sy.model.Tuser;

public interface UserDaoI {
     /**
          * 保存用戶
          * @param user
          * @return
          */
         Serializable save(Tuser user); 

}

在src/main/java中創建sy.dao.impl包,在包中編寫 UserDaoImpl實現類,如下圖所示:
這裏寫圖片描述
代碼:

package sy.dao.impl;

import java.io.Serializable;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import sy.dao.UserDaoI;
import sy.model.Tuser;

@Repository("userDao")
public class UserDaoImpl implements UserDaoI{

      /**
     * 使用@Autowired註解將sessionFactory注入到UserDaoImpl中
     */
    @Autowired
    private SessionFactory sessionFactory;

    @Override
    public Serializable save(Tuser user) {
        // TODO Auto-generated method stub
        return this.sessionFactory.getCurrentSession().save(user);
    }

}

這裏使用@Repository(“userDao”)註解完成dao注入, 使用@Autowired註解將sessionFactory注入到UserDaoImpl中。

4、在之前創建好的UserServiceI接口中添加一個save方法的定義,如下:

package sy.service;

import java.io.Serializable;

import sy.model.Tuser;

public interface UserserviceI {

    public void test1();

    Serializable save(Tuser user); 

}

5、在UserServiceImpl類中實現save方法,如下:

package sy.service.impl;

import java.io.Serializable;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import sy.dao.UserDaoI;
import sy.model.Tuser;
import sy.service.UserserviceI;


//使用Spring提供的@Service註解將UserServiceImpl標註爲一個Service
@Service("userService")
public class UserserviceImpl implements UserserviceI {

    /**
     * 注入userDao
     */
    private UserDaoI userDao;

    public UserDaoI getUserDao() {
        return userDao;
    }
    @Autowired
    public void setUserDao(UserDaoI userDao) {
        this.userDao = userDao;
    }

    public void test1() {
        System.out.print("ssss");

    }
    @Override
    public Serializable save(Tuser user) {
        // TODO Auto-generated method stub
        return userDao.save(user);
    }

}

6、在src/main/test下的me.gacl.test包中編寫 TestHibernate類,代碼如下:

package yf.test;

import java.util.Date;
import java.util.UUID;

import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import sy.model.Tuser;
import sy.service.UserserviceI;

public class TestHibernate {
      private UserserviceI userService;

        /**
         * 這個before方法在所有的測試方法之前執行,並且只執行一次
         * 所有做Junit單元測試時一些初始化工作可以在這個方法裏面進行
         * 比如在before方法裏面初始化ApplicationContext和userService
         */
        @Before
        public void before(){
            ApplicationContext ac = new ClassPathXmlApplicationContext(new String[]{"spring.xml","spring-hibernate.xml"});
            userService = (UserserviceI) ac.getBean("userService");
        }

        @Test
        public void testSaveMethod(){
            //ApplicationContext ac = new ClassPathXmlApplicationContext(new String[]{"spring.xml","spring-hibernate.xml"});
            //UserServiceI userService = (UserServiceI) ac.getBean("userService");
            Tuser user = new Tuser();
            user.setId(UUID.randomUUID().toString().replaceAll("-", ""));
            user.setName("yy");
            user.setPwd("123456");
            user.setCreatedatetime(new Date()); 
            userService.save(user);
        }

}

執行Junit單元測試,如下所示:

這裏寫圖片描述

 測試通過,再看看sshe數據庫,如下圖所示:
 
 這裏寫圖片描述

 Hibernate在執行過程中,先幫我們在ssh數據庫中創建一張tuser表,tuser的表結構根據Tuser實體類中的屬性定義來創建的,然後再將數據插入到tuser表中.
 tuser表數據如下圖所示:
 
 這裏寫圖片描述

到此,Hibernate4開發環境的搭建並且與Spring整合的工作算是全部完成並且測試通過了。

**注意:如果你執行maven install ,將TestSpring裏的內容註釋,否則會報錯:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘userDao’。**

發佈了45 篇原創文章 · 獲贊 13 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章