MyBatis3整合Spring3、SpringMVC3

開發環境:

System:Windows

WebBrowser:IE6+、Firefox3+

JavaEE Server:tomcat5.0.2.8、tomcat6

IDE:eclipse、MyEclipse 8

Database:MySQL

開發依賴庫:

JavaEE5、Spring 3.0.5、Mybatis 3.0.4、myBatis-spring-1.0、junit4.8.2

Email:[email protected]

Blog:http://blog.csdn.net/IBM_hoojo

http://hoojo.cnblogs.com/

1、 首先新建一個WebProject 命名爲MyBatisForSpring,新建項目時,使用JavaEE5的lib庫。然後手動添加需要的jar包,所需jar包如下:

clip_image002

2、 添加spring的監聽及springMVC的核心Servlet,web.xml內容,內容如下:

<-- 加載Spring容器配置 -->
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>
 
<-- 設置Spring容器加載配置文件路徑 -->
<context-param>
    <param-name>contextConfigLocationparam-name>
    <param-value>classpath*:applicationContext-*.xmlparam-value>
context-param>
 
<-- 配置Spring核心控制器 -->
<servlet>
    <servlet-name>dispatcherservlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
    <init-param>
        <param-name>contextConfigLocationparam-name>
        <param-value>/WEB-INF/dispatcher.xmlparam-value>
    init-param>
    <load-on-startup>1load-on-startup>
servlet>
 
<servlet-mapping>
    <servlet-name>dispatcherservlet-name>
    <url-pattern>*.dourl-pattern>
servlet-mapping>
 
<-- 解決工程編碼過濾器 -->
<filter>
    <filter-name>characterEncodingFilterfilter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
    <init-param>
        <param-name>encodingparam-name>
        <param-value>UTF-8param-value>
    init-param>
filter>
 
<filter-mapping>
    <filter-name>characterEncodingFilterfilter-name>
    <url-pattern>/*url-pattern>
filter-mapping>

3、 在WEB-INF目錄中添加dispatcher.xml,內容如下:

xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    <-- 註解探測器 -->
    <context:component-scan base-package="com.hoo"/>
    
    <--  annotation默認的方法映射適配器 -->
    <bean id="handlerMapping" class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
 
    <bean id="handlerAdapter" class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
beans>

4、 在src目錄下添加applicationContext-common.xml,內容如下:

xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:aop="http://www.springframework.org/schema/aop" 
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
    http://www.springframework.org/schema/aop 
    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd 
    http://www.springframework.org/schema/tx  
    http://www.springframework.org/schema/tx/spring-tx-3.0.xsd ">
    
    <-- 配置DataSource數據源 -->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://10.0.0.131:3306/ash2"/>
        <property name="username" value="dev"/>
        <property name="password" value="dev"/>
    bean>
    
    <-- 配置SqlSessionFactoryBean -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="classpath:mybatis.xml"/>
        <-- mapper和resultmap配置路徑 -->
        <property name="mapperLocations">
            <list>
                <-- 表示在com.hoo.resultmap包或以下所有目錄中以-resultmap.xml結尾所有文件 -->
                <value>classpath:com/hoo/resultmap/**/*-resultmap.xmlvalue>
                <value>classpath:com/hoo/entity/*-resultmap.xmlvalue>
                <value>classpath:com/hoo/mapper/**/*-mapper.xmlvalue>
            list>
        property>
    bean>
    
    <-- 單獨配置一個Mapper這種模式就是得給每個mapper接口配置一個bean -->
    <-- 
    <bean id="accountMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"> 
        <property name="mapperInterface" value="com.hoo.mapper.AccountMapper" />
        <property name="sqlSessionFactory" ref="sqlSessionFactory" /> 
    bean> 
    
    <bean id="companyMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"> 
        <property name="mapperInterface" value="com.hoo.mapper.CompanyMapper" />
        <property name="sqlSessionFactory" ref="sqlSessionFactory" /> 
    bean>
     --> 
    
    <-- 通過掃描的模式掃描目錄在com/hoo/mapper目錄下所有的mapper都繼承SqlMapper接口的接口這樣一個bean就可以了 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.hoo.mapper"/>
        <property name="markerInterface" value="com.hoo.mapper.SqlMapper"/>
    bean>
beans>

上面的配置最先配置的是DataSource,這裏採用的是jdbc的DataSource;

然後是SqlSessionFactoryBean,這個配置比較關鍵。SqlSessionFactoryBean需要注入DataSource數據源,其次還要設置configLocation也就是mybatis的xml配置文件路徑,完成一些關於mybatis的配置,如settings、mappers、plugin等;

如果使用mapperCannerConfigurer模式,需要設置掃描根路徑也就是你的mybatis的mapper接口所在包路徑;凡是markerInterface這個接口的子接口都參與到這個掃描,也就是說所有的mapper接口繼承這個SqlMapper。

如果你不使用自己的transaction事務,就使用MapperScannerConfigurer來完成SqlSession的打開、關閉和事務的回滾操作。在此期間,出現數據庫操作的如何異常都會被轉換成DataAccessException,這個異常是一個抽象的類,繼承RuntimeException;

5、 SqlMapper內容如下:

package com.hoo.mapper;
 
/**
 * function:所有的Mapper繼承這個接口
 * @author hoojo
 * @createDate 2011-4-12 下午04:00:31
 * @file SqlMapper.java
 * @package com.hoo.mapper
 * @project MyBatisForSpring
 * @blog http://blog.csdn.net/IBM_hoojo
 * @email [email protected]
 * @version 1.0
 */
public interface SqlMapper {
 
}

6、 實體類和ResultMap.xml

package com.hoo.entity;
 
import java.io.Serializable;
import javax.persistence.Entity;
 
@Entity
public class Account implements Serializable {
 
    private static final long serialVersionUID = -7970848646314840509L;
 
    private Integer accountId;
    private Integer status;
    private String username;
    private String password;
    private String salt;
    private String email;
    private Integer roleId;
    
    //getter、setter
 
    @Override
    public String toString() {
        return this.accountId + "#" + this.status + "#" + this.username +  "#" + 
            this.password +  "#" + this.email +  "#" + this.salt + "#" + this.roleId;
    }
}

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="status" column="status"/>
    resultMap>
mapper>

7、 在src目錄中添加applicationContext-beans.xml內容如下:

xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    <-- 註解探測器在JUnit測試的時候需要-->
    <context:component-scan base-package="com.hoo"/>
    
beans>

這裏配置bean對象,一些不能用annotation註解的對象就可以配置在這裏

8、 在src目錄中添加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>
    <-- 別名 -->
    <typeAliases>
        <typeAlias type="com.hoo.entity.Account" alias="account"/>
    typeAliases>
configuration>

在這個文件放置一些全局性的配置,如handler、objectFactory、plugin、以及mappers的映射路徑(由於在applicationContext-common中的SqlSessionFactoryBean有配置mapper的location,這裏就不需要配置)等

9、 AccountMapper接口,內容如下:

package com.hoo.mapper;
 
import java.util.List;
import org.apache.ibatis.annotations.Select;
import com.hoo.entity.Account;
 
/**
 * function:繼承SqlMapper,MyBatis數據操作接口;此接口無需實現類
 * @author hoojo
 * @createDate 2010-12-21 下午05:21:20
 * @file AccountMapper.java
 * @package com.hoo.mapper
 * @project MyBatis
 * @blog http://blog.csdn.net/IBM_hoojo
 * @email [email protected]
 * @version 1.0
 */
public interface AccountMapper extends SqlMapper {
    
    public List getAllAccount();
    
    public Account getAccount();
    
    public Account getAccountById(String id);
    
    public Account getAccountByNames(String spring);
    
    @Select("select * from account where username = #{name}")
    public Account getAccountByName(String name);
    
    public void addAccount(Account account);
    
    public void editAccount(Account account);
    
    public void removeAccount(int id);
}

這個接口我們不需要實現,由mybatis幫助我們實現,我們通過mapper文件配置sql語句即可完成接口的實現。然後這個接口需要繼承SqlMapper接口,不然在其他地方就不能從Spring容器中拿到這個mapper接口,也就是說當我們注入這個接口的時候將會失敗。

當然,你不繼承這個接口也可以。那就是你需要給買個mapper配置一個bean。配置方法如下:

<bean id="accountMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"> 
    <property name="mapperInterface" value="com.hoo.mapper.AccountMapper" />
    <property name="sqlSessionFactory" ref="sqlSessionFactory" /> 
bean>

這裏的MapperFactoryBean可以幫助我們完成Session的打開、關閉等操作

10、 在com.hoo.mapper也就是在AccountMapper接口的同一個包下,添加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">
<-- namespace和定義的Mapper接口對應並實現其中的方法 -->
<mapper namespace="com.hoo.mapper.AccountMapper">
    <-- id和mapper接口中的方法名對應resultType使用mybatis.xml中的別名 -->
    <select id="getAccount" resultType="account">
        [CDATA[
            select * from account limit 1
        ]]>
    select>
    
    <select id="getAllAccount" resultType="list" resultMap="accountResultMap">
        [CDATA[
            select * from account
        ]]>
    select>
    
    <-- accountResultMap是account-resultmap.xml中定義的resultmap -->
    <select id="getAccountById" parameterType="string" resultType="com.hoo.entity.Account" resultMap="accountResultMap">
        [CDATA[
            select * from account where account_id = #{id}
        ]]>
    select>
    
    <-- accountMap.accountResultMap是account-resultmap.xml中定義的resultmap通過namespace.id找到 -->
    <select id="getAccountByNames" parameterType="string" resultMap="accountMap.accountResultMap">
        [CDATA[
            select * from account where username = #{name}
        ]]>
    select>
    
    <sql id="user_name_pwd">
        username, password
    sql>
    
    <-- 自動生成id策略 -->
    <insert id="addAccount" useGeneratedKeys="true" keyProperty="account_id" parameterType="account">
        insert into account(account_id, status, username, password)
        values(#{accountId}, #{status}, #{username}, #{password})
    insert>
    
    <-- 根據selectKey語句生成主鍵 -->
    <insert id="addAccount4Key" parameterType="account">
        <selectKey keyProperty="account_id" order="BEFORE" resultType="int">
            select cast(random() * 10000 as Integer) a from #Tab
        selectKey>
        insert into account(account_id, status, username, password)
        values(#{accountId}, #{status}, #{username}, #{password})
    insert>
    
    <update id="editAccount" parameterType="account">
        update account set
        status = #{status},
        username = #{username},
        password = #{password}
        where account_id = #{accountId}
    update>
    
    <delete id="removeAccount" parameterType="int">
        delete from account where account_id = #{id}
    delete>
mapper>

上面的namespace和定義接口類路徑對應,所有的sql語句,如select、insert、delete、update的id和方法名稱對應。關於更多MyBatis內容的講解,這裏就不贅述的。這裏只完成整合!如果你不懂可以去閱讀其他關於MyBatis的資料。

11、 爲了測試發佈,這裏使用junit和spring官方提供的spring-test.jar,完成spring框架整合的測試,代碼如下:

package com.hoo.mapper;
 
import java.util.List;
import javax.inject.Inject;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit38.AbstractJUnit38SpringContextTests;
import com.hoo.entity.Account;
 
/**
 * function: AccountMapper JUnit測試類
 * @author hoojo
 * @createDate 2011-4-12 下午04:21:50
 * @file AccountMapperTest.java
 * @package com.hoo.mapper
 * @project MyBatisForSpring
 * @blog http://blog.csdn.net/IBM_hoojo
 * @email [email protected]
 * @version 1.0
 */
 
@ContextConfiguration("classpath:applicationContext-*.xml")
public class AccountMapperTest extends AbstractJUnit38SpringContextTests {
    
    @Inject
    //@Named("accountMapper")
    private AccountMapper mapper;
    
    public void testGetAccount() {
        System.out.println(mapper.getAccount());
    }
    
    public void testGetAccountById() {
        System.out.println(mapper.getAccountById("28"));
    }
    
    public void testGetAccountByName() {
        System.out.println(mapper.getAccountByName("user"));
    }
    
    public void testGetAccountByNames() {
        System.out.println(mapper.getAccountByNames("user"));
    }
    
    public void testAdd() {
        Account account = new Account();
        account.setEmail("[email protected]");
        account.setPassword("abc");
        account.setRoleId(1);
        account.setSalt("ss");
        account.setStatus(0);
        account.setUsername("Jack");
        mapper.addAccount(account);
    }
    
    public void testEditAccount() {
        Account acc = mapper.getAccountByNames("Jack");
        System.out.println(acc);
        acc.setUsername("Zhangsan");
        acc.setPassword("123123");
        mapper.editAccount(acc);
        System.out.println(mapper.getAccountById(acc.getAccountId() + ""));
    }
    
    public void testRemoveAccount() {
        Account acc = mapper.getAccountByNames("Jack");
        mapper.removeAccount(acc.getAccountId());
        System.out.println(mapper.getAccountByNames("Jack"));
    }
    
    public void testAccountList() {
        List acc = mapper.getAllAccount();
        System.out.println(acc.size());
        System.out.println(acc);
    }
}

這裏的注入並沒有使用@Autowired、@Resource、@Qualifier注入,而是使用@Inject、@Named注入方式,Inject注入是JSR330的標準注入方式;而不侷限於某個產品,使用於多個產品的使用,推薦使用這種方式;運行後,沒有發現問題,就可以繼續後續的編碼工作了。

12、 定義AccountDao接口及實現代碼,代碼如下:

package com.hoo.dao;
 
import java.util.List;
import org.springframework.dao.DataAccessException;
 
/**
 * function: Account數據庫操作dao接口
 * @author hoojo
 * @createDate 2011-4-13 上午10:21:38
 * @file AccountDao.java
 * @package com.hoo.dao
 * @project MyBatisForSpring
 * @blog http://blog.csdn.net/IBM_hoojo
 * @email [email protected]
 * @version 1.0
 */
public interface AccountDao {
    
    /**
     * function: 添加Account對象信息
     * @author hoojo
     * @createDate 2011-4-13 上午11:50:05
     * @param entity Account
     * @return boolean 是否成功
     * @throws DataAccessException
     */
    public boolean addAccount(T entity) throws DataAccessException;
    
    /**
     * function: 根據id對到Account信息
     * @author hoojo
     * @createDate 2011-4-13 上午11:50:45
     * @param id 編號id
     * @return Account
     * @throws DataAccessException
     */
    public T getAccount(Integer id) throws DataAccessException;
    
    /**
     * function: 查詢所有Account信息
     * @author hoojo
     * @createDate 2011-4-13 上午11:51:45
     * @param id 編號id
     * @return Account
     * @throws DataAccessException
     */
    public List getList() throws DataAccessException;
}

接口實現

package com.hoo.dao.impl;
 
import java.util.List;
import javax.inject.Inject;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Repository;
import com.hoo.dao.AccountDao;
import com.hoo.entity.Account;
import com.hoo.mapper.AccountMapper;
 
/**
 * function: Account數據庫操作dao
 * @author hoojo
 * @createDate 2011-4-13 上午10:25:02
 * @file AccountDaoImpl.java
 * @package com.hoo.dao.impl
 * @project MyBatisForSpring
 * @blog http://blog.csdn.net/IBM_hoojo
 * @email [email protected]
 * @version 1.0
 */
@SuppressWarnings("unchecked")
@Repository
public class AccountDaoImplextends Account> implements AccountDao {
    
    @Inject
    private AccountMapper mapper;
    
    public boolean addAccount(T entity) throws DataAccessException {
        boolean flag = false;
        try {
            mapper.addAccount(entity);
            flag = true;
        } catch (DataAccessException e) {
            flag = false;
            throw e;
        }
        return flag;
    }
 
    public T getAccount(Integer id) throws DataAccessException {
        T entity = null;
        try {
            entity = (T) mapper.getAccountById(String.valueOf(id));
        } catch (DataAccessException e) {
            throw e;
        }
        return entity;
    }
 
    public List getList() throws DataAccessException {
        return (List) mapper.getAllAccount();
    }
}

13、 服務層AccountBiz接口及實現代碼

接口:

package com.hoo.biz;
 
import java.util.List;
import org.springframework.dao.DataAccessException;
 
/**
 * function: biz層Account接口
 * @author hoojo
 * @createDate 2011-4-13 上午11:33:04
 * @file AccountBiz.java
 * @package com.hoo.biz
 * @project MyBatisForSpring
 * @blog http://blog.csdn.net/IBM_hoojo
 * @email [email protected]
 * @version 1.0
 */
public interface AccountBiz {
    /**
     * function: 添加Account對象信息
     * @author hoojo
     * @createDate 2011-4-13 上午11:50:05
     * @param entity Account
     * @return boolean 是否成功
     * @throws DataAccessException
     */
    public boolean addAccount(T entity) throws DataAccessException;
    
    /**
     * function: 根據id對到Account信息
     * @author hoojo
     * @createDate 2011-4-13 上午11:50:45
     * @param id 編號id
     * @return Account
     * @throws DataAccessException
     */
    public T getAccount(Integer id) throws DataAccessException;
    
    /**
     * function: 查詢所有Account信息
     * @author hoojo
     * @createDate 2011-4-13 上午11:51:45
     * @param id 編號id
     * @return Account
     * @throws DataAccessException
     */
    public List getList() throws DataAccessException;
}

實現代碼:

package com.hoo.biz.impl;
 
import java.util.List;
import javax.inject.Inject;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import com.hoo.biz.AccountBiz;
import com.hoo.dao.AccountDao;
import com.hoo.entity.Account;
import com.hoo.exception.BizException;
 
/**
 * function: Account Biz接口實現
 * @author hoojo
 * @createDate 2011-4-13 上午11:34:39
 * @file AccountBizImpl.java
 * @package com.hoo.biz.impl
 * @project MyBatisForSpring
 * @blog http://blog.csdn.net/IBM_hoojo
 * @email [email protected]
 * @version 1.0
 */
//@Component
@Service
public class AccountBizImplextends Account> implements AccountBiz {
    
    @Inject
    private AccountDao dao;
    
    public boolean addAccount(T entity) throws DataAccessException {
        if (entity == null) {
            throw new BizException(Account.class.getName() + "對象參數信息爲Empty!");
        }
        return dao.addAccount(entity);
    }
 
    public T getAccount(Integer id) throws DataAccessException {
        return dao.getAccount(id);
    }
 
    public List getList() throws DataAccessException {
        return dao.getList();
    }
}

上面用到了一個自定義的異常信息,代碼如下:

package com.hoo.exception;
 
import org.springframework.dao.DataAccessException;
 
/**
 * function:自定義Biz層異常信息
 * @author hoojo
 * @createDate 2011-4-13 上午11:42:19
 * @file BizException.java
 * @package com.hoo.exception
 * @project MyBatisForSpring
 * @blog http://blog.csdn.net/IBM_hoojo
 * @email [email protected]
 * @version 1.0
 */
public class BizException extends DataAccessException {
 
    /**
     * @author Hoojo
     */
    private static final long serialVersionUID = 1L;
    
    public BizException(String msg) {
        super(msg);
    }
 
    public BizException(String msg, Throwable cause) {
        super(msg, cause);
    }
}

這裏只是簡單的繼承,如果還有其他的異常業務或需求可以進行具體的實現

14、 springMVC的控制器,AccountController代碼如下:

package com.hoo.controller;
 
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import com.hoo.biz.AccountBiz;
import com.hoo.entity.Account;
 
/**
 * function: Account控制器
 * @author hoojo
 * @createDate 2011-4-13 上午10:18:02
 * @file AccountController.java
 * @package com.hoo.controller
 * @project MyBatisForSpring
 * @blog http://blog.csdn.net/IBM_hoojo
 * @email [email protected]
 * @version 1.0
 */
@Controller
@RequestMapping("/account")
public class AccountController {
    
    @Inject
    private AccountBiz biz;
    
    @RequestMapping("/add")
    public String add(Account acc) {
        System.out.println(acc);
        biz.addAccount(acc);
        return "redirect:/account/list.do";
    }
    
    @RequestMapping("/get")
    public String get(Integer id, Model model) {
        System.out.println("##ID:" + id);
        model.addAttribute(biz.getAccount(id));
        return "/show.jsp";
    }
    
    @RequestMapping("/list")
    public String list(Model model) {
        model.addAttribute("list", biz.getList());
        return "/list.jsp";
    }
    
    @ExceptionHandler(Exception.class)
    public String exception(Exception e, HttpServletRequest request) {
        //e.printStackTrace();
        request.setAttribute("exception", e);
        return "/error.jsp";
    }
}

15、 基本頁面代碼

index.jsp

"java" import="java.util.*" pageEncoding="UTF-8"%>


    
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
 
span style="color: #006080">"-//W3C//DTD HTML 4.01 Transitional//EN">



    
  
    "">
    
    MyBatis 整合  Spring 3.0.5
    "pragma" content="no-cache">
    "cache-control" content="no-cache">
    "expires" content="0">    
    "keywords" content="keyword1,keyword2,keyword3">
    "description" content="This is my page">
  
  
  
          

MyBatis 3.0.4 整合 Spring 3.0.5

        "account/list.do">查詢所有
        "account/add.do?username=abcdef&password=123132&status=2">添加
        "account/get.do?id=25">查詢
  

List.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>all Account Result</title>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
  </head>
  
  <body>
        <c:forEach items="${list}" var="data">
            id: ${data.accountId }---name: ${data.username }---password: ${data.password }<hr/> 
        </c:forEach>
  </body>
</html>

show.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>show Account</title>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
  </head>
  
  <body>
        ${account }<br/>
        ${account.username }#${account.accountId }
  </body>
</html>
 

error.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>Error Page</title>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
  </head>
  
  <body>
    <H2>Exception: ${exception }</H2> 
    <a href="javascript:document.getElementById('show').style.display = 'block';void(0);">
        詳細信息
    </a> 
    <div id="show" style="color: red; display: none;">
        <% Exception ex = (Exception)request.getAttribute("exception"); %> 
        
        <% ex.printStackTrace(new java.io.PrintWriter(out)); %>
    </div> 
  </body>
</html>

16、 以上就基本上完成了整個Spring+SpringMVC+MyBatis的整合了。如果你想添加事務管理,得在applicationContext-common.xml中加入如下配置:

<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
bean>

同時還需要加入aspectjweaver.jar這個jar包;

注意的是:Jdbc的TransactionManager不支持事務隔離級別,我在整個地方加入其它的TransactionManager,增加對transaction的隔離級別都嘗試失敗!

也許可以用於jpa、jdo、jta這方面的東西。不知道大家對MyBatis的事務是怎麼處理的?

17、 對Dao進行擴展封裝,運用SqlSessionDaoSupport進行模板的擴展或運用:

BaseDao代碼如下:

package com.hoo.dao.impl;
 
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.springframework.stereotype.Repository;
import com.hoo.dao.BaseDao;
 
/**
 * function: 運用SqlSessionDaoSupport封裝Dao常用增刪改方法,可以進行擴展
 * @author hoojo
 * @createDate 2011-4-13 下午06:33:37
 * @file BaseDaoImpl.java
 * @package com.hoo.dao.impl
 * @project MyBatisForSpring
 * @blog http://blog.csdn.net/IBM_hoojo
 * @email [email protected]
 * @version 1.0
 */
@Repository
@SuppressWarnings({ "unchecked", "unused" })
public class BaseDaoImplextends Object> extends SqlSessionDaoSupport implements BaseDao {
    
    @Inject
    private SqlSessionFactory sqlSessionFactory;
    
    public boolean add(String classMethod, T entity) throws Exception {
        boolean flag = false;
        try {
            flag = this.getSqlSession().insert(classMethod, entity) > 0 ? true : false;
        } catch (Exception e) {
            flag = false;
            throw e;
        }
        return flag;
    }
 
    public boolean edit(String classMethod, T entity) throws Exception {
        boolean flag = false;
        try {
            flag = this.getSqlSession().update(classMethod, entity) > 0 ? true : false;
        } catch (Exception e) {
            flag = false;
            throw e;
        }
        return flag;
    }
 
    public T get(String classMethod, T entity) throws Exception {
        T result = null;
        try {
            result = (T) this.getSqlSession().selectOne(classMethod, entity);
        } catch (Exception e) {
            throw e;
        }
        return result;
    }
 
    public List getAll(String classMethod) throws Exception {
        List result = new ArrayList();
        try {
            result = this.getSqlSession().selectList(classMethod);
        } catch (Exception e) {
            throw e;
        }
        return result;
    }
 
    public boolean remove(String classMethod, T entity) throws Exception {
        boolean flag = false;
        try {
            flag = this.getSqlSession().delete(classMethod, entity) > 0 ? true : false;
        } catch (Exception e) {
            flag = false;
            throw e;
        }
        return flag;
    }
}

值得說明的是,這個類繼承了SqlSessionDaoSupport,它需要我們幫助它注入SqlSessionFactory或是SqlSessionTemplate,如果兩者都被注入將忽略SqlSessionFactory屬性,使用SqlSessionTemplate模板。

繼承SqlSessionDaoSupport後,可以拿到SqlSession完成數據庫的操作;

18、 對Dao進行擴展封裝,運用SqlSessionTemplate進行模板的擴展或運用:

首先看看這個組件中運用的一個Mapper的基類接口:

package com.hoo.mapper;
 
import java.util.List;
import org.springframework.dao.DataAccessException;
 
/**
 * function: BaseSqlMapper繼承SqlMapper,對Mapper進行接口封裝,提供常用的增刪改查組件;
 * 也可以對該接口進行擴展和封裝
 * @author hoojo
 * @createDate 2011-4-14 上午11:36:41
 * @file BaseSqlMapper.java
 * @package com.hoo.mapper
 * @project MyBatisForSpring
 * @blog http://blog.csdn.net/IBM_hoojo
 * @email [email protected]
 * @version 1.0
 */
public interface BaseSqlMapper extends SqlMapper {
    
    public void add(T entity) throws DataAccessException;
    
    public void edit(T entity) throws DataAccessException;
    
    public void remvoe(T entity) throws DataAccessException;
    
    public T get(T entity) throws DataAccessException;
    
    public List getList(T entity) throws DataAccessException;
}

該接口繼承SqlMapper接口,但是該接口沒有MyBatis的mapper實現。需要我們自己的業務mapper繼承這個接口,完成上面的方法的實現。

看看繼承SqlSessionTemplate的BaseMapperDao代碼:

package com.hoo.dao.impl;
 
import java.util.List;
import javax.inject.Inject;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.stereotype.Repository;
import com.hoo.dao.BaseMapperDao;
import com.hoo.mapper.BaseSqlMapper;
 
/**
 * function:運用SqlSessionTemplate封裝Dao常用增刪改方法,可以進行擴展
 * @author hoojo
 * @createDate 2011-4-14 下午12:22:07
 * @file BaseMapperDaoImpl.java
 * @package com.hoo.dao.impl
 * @project MyBatisForSpring
 * @blog http://blog.csdn.net/IBM_hoojo
 * @email [email protected]
 * @version 1.0
 */
@SuppressWarnings("unchecked")
@Repository
public class BaseMapperDaoImpl extends SqlSessionTemplate implements BaseMapperDao {
    
    @Inject
    public BaseMapperDaoImpl(SqlSessionFactory sqlSessionFactory) {
        super(sqlSessionFactory);
    }
    
    private Class extends BaseSqlMapper> mapperClass;
    
    public void setMapperClass(Class extends BaseSqlMapper> mapperClass) {
        this.mapperClass = mapperClass;
    }
 
    private BaseSqlMapper getMapper() {
        return this.getMapper(mapperClass);
    }
    
    public boolean add(T entity) throws Exception {
        boolean flag = false;
        try {
            this.getMapper().add(entity);
            flag = true;
        } catch (Exception e) {
            flag = false;
            throw e;
        }
        return flag;
    }
 
    public boolean edit(T entity) throws Exception {
        boolean flag = false;
        try {
            this.getMapper().edit(entity);
            flag = true;
        } catch (Exception e) {
            flag = false;
            throw e;
        }
        return flag;
    }
 
    public T get(T entity) throws Exception {
        return this.getMapper().get(entity);
    }
 
    public List getAll() throws Exception {
        return this.getMapper().getList(null);
    }
 
    public boolean remove(T entity) throws Exception {
        boolean flag = false;
        try {
            this.getMapper().remvoe(entity);
            flag = true;
        } catch (Exception e) {
            flag = false;
            throw e;
        }
        return flag;
    }
}

上面這個類繼承了SqlSessionTemplate,這個類需要提供一個構造函數。這裏提供的是SqlSessionFactory的構造函數,通過該函數注入SqlSessionFactory即可完成數據庫操作;

例外的是這個類還有一個關鍵屬性mapperClass,這個class需要是BaseSqlMapper接口或是子接口,然後通過SqlSessionTemplate模板獲得當前設置的Class的Mapper對象,完成數據庫操作。

該類的測試代碼:

@ContextConfiguration("classpath:applicationContext-*.xml")
public class BaseMapperDaoImplTest extends AbstractJUnit38SpringContextTests {
    
    @Inject
    private BaseMapperDao dao;
    
    public void init() {
        dao.setMapperClass(CompanyMapper.class);
    }
    
    public void testGet() throws Exception {
        init();
        Company c = new Company();
        c.setCompanyId(4);
        System.out.println(dao.get(c));
    }
    
    public void testAdd() throws Exception {
        init();
        Company c = new Company();
        c.setAddress("北京中關村");
        c.setName("beijin");
        System.out.println(dao.add(c));
    }
}

一般情況下,你可以在一個Dao中注入BaseMapperDao,緊跟着需要設置MapperClass。只有設置了MapperClass後,BaseMapperDao才能獲取對應mapper,完成相關的數據庫操作。當然你可以在這個Dao中將SqlSessionTemplate、SqlSession暴露出來,當BaseMapperDao的方法不夠用,可以進行擴展。

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