spring,structs2和Mybatis整合以及單元測試

最近一個項目使用的是struts2+Spring3+mybatis3的技術框架,由於開發人員都不熟悉如何進行單元測試,今天有空,簡單研究了一下如何用junit4來測試基於這個框架的代碼。由於struts的action只是負責前臺的請求轉發,而所有的業務都是在service層處理,因此一般情況下只需對service進行單元測試,而不需要對action進行單元測試。下面介紹一個簡單的例子:

開發環境:

SystemWindows xp
IDEeclipse Java EE 3.6
DatabaseMySQL

開發依賴庫:

JavaEE5Spring 3.0.5Mybatis 3.0.4myBatis-spring-1.0junit4.8.1

一、準備工作:

1、下載jar
Spring3 jar下載:

http://ebr.springsource.com/repository/app/library/version/detail?name=org.springframework.spring&version=3.0.5.RELEASE

MyBatis3 jar 下載:
http://www.mybatis.org/java.html
junit 4 jar下載:
http://www.junit.org/

 

2、 添加的jar包如下:


3、創建mysql的數據庫表,步驟如下:

1、進入mysql的安裝路徑,假設在:C:\Program Files\MySQL\MySQL Server 5.1\bin;
2、輸入命令:mysql -uroot -p,enter,輸入密碼:admin;
3、mysql>use test;
5、mysql>grant all privileges on test.* to test@'localhost' identified by 'test';
6、mysql>flush privileges;

4、mysql>
  create table account_bak(account_id int not null auto_increment,
                     username varchar(20),
                     password varchar(20),
                     create_time datetime,
                     primary key(account_id));


二、spring 和mybatis整合
1、在eclipse中創建一個java project,目錄結構如下:


這是一個標準的maven工程的目錄結構,下面逐一介紹上圖涉及到的文件。
2、創建mybatis的配置文件mybatis.xml

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>

   

</configuration>

上面的配置文件中,可以加入一些公共、常用的MyBatis方面的全局配置。handlerobjectFactoryplugin、以及mappers的映射路徑(由於在spring配置文件spring.xml中的SqlSessionFactoryBean有配置mapperlocation,這裏就不需要配置)等。這個文件名稱和下面的spring.xml中的configLocation中的值對應,不是隨便寫的。
3、創建spring的配置文件spring.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:p="http://www.springframework.org/schema/p"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
 xsi:schemaLocation="
   http://www.springframework.org/schema/beans 
   http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
   http://www.springframework.org/schema/context 
   http://www.springframework.org/schema/context/spring-context-2.5.xsd
   http://www.springframework.org/schema/jee 
   http://www.springframework.org/schema/jee/spring-jee-2.5.xsd
   http://www.springframework.org/schema/tx 
   http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">

 <bean
  class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" />
 
 <bean id="dataSource"
  class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  <property name="driverClassName" value="com.mysql.jdbc.Driver" />
  <property name="url" value="jdbc:mysql://localhost:3306/test?useUnicode=true&amp;characterEncoding=UTF-8" />
  <property name="username" value="test" />
  <property name="password" value="test" />
 </bean>
 
 <!-- 配置事務管理器,注意這裏的dataSource和SqlSessionFactoryBean的dataSource要一致,不然事務就沒有作用了 -->
 <bean id="transactionManager"
  class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  <property name="dataSource" ref="dataSource" />
 </bean>

 <tx:annotation-driven transaction-manager="transactionManager" />
 <!-- myBatis文件 -->

 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  <property name="configLocation" value="classpath:mybatis.xml" />
  <property name="mapperLocations"
   value="classpath*:com/glen/model/*.xml" />
  <property name="dataSource" ref="dataSource" />
 </bean>
 
 <bean id="accountDao" class="com.glen.dao.AccountDao">
  <property name="sessionFactory" ref="sqlSessionFactory"/>
 </bean>
 
 <bean id="accountService" class="com.glen.service.AccountService">
  <property name="accountDao" ref="accountDao"/>
 </bean>
 
 <context:annotation-config />
 <context:component-scan base-package="com.glen" />

</beans>

4、JavaBeanModelEntity)相關類、及mybatis 的mapper對象

javabean:

package com.glen.model;

import java.io.Serializable;
import java.util.Date;

public class Account implements Serializable {

 private static final long serialVersionUID = -7970848646314840509L;
 
 private Integer accountId;
 private String username;
 private String password;
 private Date createTime;

 public Account() {
  super();
 }
//下面是getter、setters

account-resultMap.xml

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"

    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="accountMap">

    <resultMap type="com.hoo.entity.Account" id="accountResultMap">

       <id property="accountId" column="account_id"/>

       <result property="username" column="username"/>

       <result property="password" column="password"/>

       <result property="createTime" column="create_time"/>

    </resultMap>

</mapper>

 

account-mapper.xml

 

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 
 "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="account">

 
 <select id="getList" parameterType="com.glen.model.Account" resultType="list" resultMap="accountResultMap">
   select * from account where username like '%' #{username} '%'
 </select>
 
 <select id="getAllAccount" resultType="list" resultMap="accountResultMap">
   select * from account
 </select>
  
 
 <!-- accountResultMap是account-resultmap.xml中定義的resultmap -->
 <select id="get" parameterType="com.glen.model.Account" resultType="com.glen.model.Account" resultMap="accountResultMap">
  <![CDATA[
   select * from account where account_id = #{accountId}
        ]]>
 </select>
 
 
 <!-- 自動生成id策略 -->
 <insert id="add" useGeneratedKeys="true" keyProperty="accountId" parameterType="com.glen.model.Account">
  insert into account(account_id, username, password)
  values(#{accountId,jdbcType=BIGINT}, #{username}, #{password})
<!--將最後插入的逐漸返回到java對象-->
  <selectKey resultType="int" keyProperty="accountId">
   SELECT LAST_INSERT_ID()
  </selectKey>
  
 </insert>
  
 <update id="edit" parameterType="com.glen.model.Account">
  update account set
  username = #{username},
  password = #{password}
  where account_id = #{accountId}
 </update>
 
 <delete id="remove" parameterType="com.glen.model.Account">
  delete from account where account_id = #{accountId}
 </delete>
  
</mapper> 


5、創建dao:

 

package com.glen.dao;

import javax.annotation.Resource;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.stereotype.Repository;

import com.glen.model.Account;


public class AccountDao {

 private SqlSessionFactory sessionFactory;

 public AccountDao() {

 }

 public SqlSessionFactory getSessionFactory() {
  return sessionFactory;
 }

 public void setSessionFactory(SqlSessionFactory sessionFactory) {
  this.sessionFactory = sessionFactory;
 }

 public void insert(Account account) {

  SqlSession session = sessionFactory.openSession();
  session.insert("account.add", account);
 }
 
 public Account getAccountById(Account account) {
  
  SqlSession session = sessionFactory.openSession();
  Account accountFromDb = (Account)session.selectOne("account.get", account);
  return accountFromDb;
 }
}

 

6、創建service:

 

package com.glen.service;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.glen.dao.AccountDao;
import com.glen.model.Account;


public class AccountService {
 
 private AccountDao accountDao;
 
 /**
  * 新增一個帳戶。
  * @param account
  */
 public void insertAccount(Account account) {
  
  accountDao.insert(account);
 }

 /**
  * 根據帳戶ID查找帳戶信息
  * @param account
  * @return
  */
 public Account getAccountById(Account account) {
  
  return accountDao.getAccountById(account);
 }
 
 public AccountDao getAccountDao() {
  return accountDao;
 }

 public void setAccountDao(AccountDao accountDao) {
  this.accountDao = accountDao;
 }
}

 


Ok,至此spring 和mybatis就整合好了。

三、用junit進行單元測試
在src/test/java目錄下,創建一個測試類:TestAccountService:

 

package com.glen.service;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

import org.apache.log4j.Logger;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

import com.glen.model.Account;


public class TestAccountService {
 
 Logger logger = Logger.getLogger("TestAccountService");
 
 AccountService service = null;

 @Before
 public void init() {
  
  ApplicationContext aCtx = new FileSystemXmlApplicationContext(
    "classpath:spring.xml");
  AccountService service = (AccountService) aCtx
    .getBean("accountService");
  assertNotNull(service);
  this.service = service;

 }
 
 @Test
 public void testInsertAccount() {

  // 創建一個帳戶
  Account account = new Account();
  // account.setAccountId(1);
  account.setUsername("selina");
  account.setPassword("123456");
  
  //將創建的帳戶插入到數據庫中
  service.insertAccount(account);
  logger.debug("account id: " + account.getAccountId());
  
  //從數據庫獲取剛纔插入的帳戶
  Account accountFromDb = service.getAccountById(account);
  assertNotNull(accountFromDb);
  assertEquals(account.getAccountId(), accountFromDb.getAccountId());
 }

}


測試通過,顯示如下界面:


四、使用spring的標記來注入對象
如上所述,我們在spring的配置文件spring.xml中,定義了兩個業務模塊相關的bean,accountDao和accountService,但是在實際項目中,這樣的dao和service會非常多,如果每個都要這樣定義,會造成配置文件的體積過大,可閱讀性和可維護性都會變差。

那麼如何對spring.xml進行瘦身呢?有兩種方案,第一種方案是分模塊開發,對於模塊內部的bean,寫在對應模塊內部的spring配置文件中,如:spring-account.xml;第二種方案,就是使用spring的標記。下面我想說說的就是,用spring的標記:@Service @Repository @Resource來實現對象的注入。在上面這個例子基礎上,做以下步驟的修改:

1、註釋掉spring.xml中的兩個bean:accountDao和accountService的定義

  <!--  
 <bean id="accountDao" class="com.glen.dao.AccountDao">
  <property name="sessionFactory" ref="sqlSessionFactory"/>
 </bean>
 
 <bean id="accountService" class="com.glen.service.AccountService">
  <property name="accountDao" ref="accountDao"/>
 </bean>
 -->


2、在AccountDao類中添加兩個標記:@Repository和 @Resource,

 

@Repository
public class AccountDao {

 @Resource
 private SqlSessionFactory sessionFactory; 

這裏添加@Repository標記,相當於在spring.xml中定義了一個bean,bean的id爲這個類對象名稱的第一個字母改成小寫後的字符串,即:accountDao。添加 @Resource標記,相當於在accountDao這個bean中,引用了一個“sqlSessionFactory”。

3、在AccountService類中添加兩個標記:@Service 和 @Resource:

@Service
public class AccountService {
 
 @Resource
 private AccountDao accountDao;


4、運行TestAccountService,同樣測試通過。

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