Struts2、Spring3、MyBatis3整合ExtJS,完成ColumnTree 【一】

開發環境:

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、Struts2.2.3、junit4.8.2、ext2.2.2

Email:[email protected]

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

http://hoojo.cnblogs.com/

上次介紹過Spring3、SpringMVC、MyBatis3整合,在線博文:http://www.cnblogs.com/hoojo/archive/2011/04/15/2016324.html

一、準備工作

1、 下載jar包

Struts2 jar下載:

http://labs.renren.com/apache-mirror//struts/library/struts-2.2.3-lib.zip

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

2、 添加的jar包如下:

image

二、Spring、MyBatis整合

1、 需要的jar文件如下:

clip_image002

2、 在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>

上面的配置文件中,可以加入一些公共、常用的MyBatis方面的全局配置。如handler、objectFactory、plugin、以及mappers的映射路徑(由於在applicationContext-common中的SqlSessionFactoryBean有配置mapper的location,這裏就不需要配置)等。這個類的文件名稱和下面的applicationContext-common.xml中的configLocation中的值對應,不是隨便寫的。

3、 在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>
    
    <-- 配置事務管理器注意這裏的dataSource和SqlSessionFactoryBean的dataSource要一致不然事務就沒有作用了 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    bean>
 
    <-- 配置事務的傳播特性 -->
    <bean id="baseTransactionProxy" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean" abstract="true">
        <property name="transactionManager" ref="transactionManager" />
        <property name="transactionAttributes">
            <props>
                <prop key="add*">PROPAGATION_REQUIREDprop>
                <prop key="edit*">PROPAGATION_REQUIREDprop>
                <prop key="remove*">PROPAGATION_REQUIREDprop>
                <prop key="insert*">PROPAGATION_REQUIREDprop>
                <prop key="update*">PROPAGATION_REQUIREDprop>
                <prop key="del*">PROPAGATION_REQUIREDprop>
                <prop key="*">readOnlyprop>
            props>
        property>
    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;

SqlSessionFactory,是MyBatis團隊提供整合Spring的SqlSession工廠Bean用它可以完成Spring和MyBatis的整合。SqlSessionFactoryBean需要注入DataSource,配置myBatis配置文件的location,以及配置mapper.xml和resultMap.xml文件的路徑,可以用通配符模式配置。其實mapper裏面是可以存放resultMap的內容的。由於resultMap文件的內容是和JavaBean及數據庫表對象進行映射的。一般一張表、一個JavaBean(Model)對應一個resultMap文件。將resultMap獨立出來提供可讀性、維護性。

TransactionManager,事務管理器是採用jdbc的管理器。需要注入DataSource數據源,這裏注入的數據源和SqlSessionFactory是同一個數據源。如果不同的數據源,事務將無法起到作用。

baseTransactionProxy,事務的傳播特性纔有spring提供的TransactionProxyFactoryBean這個事務代理工廠的攔截器類來完成。其他的暫時還沒有可以支持事務配置的傳播特性和隔離級別的方法,關於這裏你可以參考:http://www.cnblogs.com/hoojo/archive/2011/04/15/2017447.html

MapperScannerConfigurer是MyBatis的mapper接口的掃描器,通過這個配置可以完成對指定basePackage報下的類進行掃描,如果這些類有繼承SqlMapper這個類的,將會是MyBatis的接口。不需要單獨配置mapper,而完成注入。

4、 在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">
    <-- 註解探測器 -->
    <context:component-scan base-package="com.hoo"/>
    
beans>

這裏面可以完成一下Action、Bean的注入配置

5、 JavaBean(Model、Entity)相關類、及resultMap.xml文件內容

Bean

package com.hoo.entity;
 
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、setter
    
    @Override
    public String toString() {
        return this.accountId + "#" + this.username +  "#" + this.password +  "#" + this.createTime;
    }
}

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>
 

resultMap的type屬性和對應的classpath對應,id會在mapper.xml文件中用到。下面的屬性property是JavaBean的屬性,column和數據庫的字段對應。

6、 上面的applicationContext-common.xml中配置了SqlMapper,下面是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 {
}

7、 定製我們自己的增刪改查(CRUD)組件,接口如下

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<T> 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<T> getList(T entity) throws DataAccessException;
}

當然實際開發中,增刪改查組件一定不止這幾個方法。這裏只是隨便挪列幾個方法做一個示例。實際中可以根據需求進行添加方法,這裏添加的方法可以用一個mapper.xml進行實現,然後注入這個mapper即可完成操作。也可以定義其他的mapper,如AccountMapper繼承這個接口。然後爲AccountMapper提供實現也是可以的。

8、 下面看看AccountMapper接口

package com.hoo.mapper;
 
import java.util.List;
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<T extends Account> extends BaseSqlMapper<T> {
    
    public List<T> getAllAccount();
}

上面的AccountMapper繼承了BaseSqlMapper,並且提供了自己所需要的方法。下面實現這個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">
<-- namespace和定義的Mapper接口對應並實現其中的方法 -->
<mapper namespace="com.hoo.mapper.AccountMapper">
 
    <select id="getList" parameterType="com.hoo.entity.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="account" resultType="com.hoo.entity.Account" resultMap="accountResultMap">
        [CDATA[
            select * from account where account_id = #{accountId}
        ]]>
    select>
    
    <-- 自動生成id策略 -->
    <insert id="add" useGeneratedKeys="true" keyProperty="account_id" parameterType="account">
        insert into account(account_id, username, password)
        values(#{accountId}, #{username}, #{password})
    insert>
    
    
    <update id="edit" parameterType="account">
        update account set
        username = #{username},
        password = #{password}
        where account_id = #{accountId}
    update>
    
    <delete id="remove" parameterType="account">
        delete from account where account_id = #{accountId}
    delete>
    
mapper>
mapper的namespace和接口的classpath對應,裏面的sql語句的id和方法名稱對應。這樣就完成了AccountMapper的實現。

9、 下面來測試下AccountMapper的功能,代碼如下:

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
    private AccountMapper<Account> mapper;
    
    public void testGetAccount() {
        Account acc = new Account();
        acc.setAccountId(28);
        System.out.println(mapper.get(acc));
    }
    
    public void testAdd() {
        Account account = new Account();
        account.setUsername("lisi@155.com");
        account.setPassword("abc");
        mapper.add(account);
    }
    
    public void testEditAccount() {
        Account acc = new Account();
        acc.setAccountId(28);
        acc = mapper.get(acc);
        System.out.println(acc);
        acc.setUsername("Zhangsan22");
        acc.setPassword("123123");
        mapper.edit(acc);
        System.out.println(mapper.get(acc));
    }
    
    public void testRemoveAccount() {
        Account acc = new Account();
        acc.setAccountId(28);
        mapper.remvoe(acc);
        System.out.println(mapper.get(acc));
    }
    
    public void testAccountList() {
        List<Account> acc = mapper.getAllAccount();
        System.out.println(acc.size());
        System.out.println(acc);
    }
    
    public void testList() {
        Account acc = new Account();
        acc.setUsername("@qq.com");
        List<Account> list = mapper.getList(acc);
        System.out.println(list.size());
        System.out.println(list);
    }
}

運行上面的方法,沒有錯誤基本上就算完成了Mapper的功能了。

10、 下面來寫一個數據庫操作的基類Dao,代碼如下:

package com.hoo.dao;
 
import java.util.List;
import com.hoo.mapper.BaseSqlMapper;
 
/**
 * function:
 * @author hoojo
 * @createDate 2011-4-14 上午11:30:09
 * @file BaseMapperDao.java
 * @package com.hoo.dao
 * @project MyBatisForSpring
 * @blog http://blog.csdn.net/IBM_hoojo
 * @email [email protected]
 * @version 1.0
 */
public interface BaseMapperDao<T> {
    
    @SuppressWarnings("unchecked")
    public void setMapperClass(Class<? extends BaseSqlMapper> mapperClass);
    
    public BaseSqlMapper<T> getMapper();
    
    public boolean add(T entity) throws Exception;
    
    public boolean edit(T entity) throws Exception;
    
    public boolean remove(T entity) throws Exception;
    
    public T get(T entity) throws Exception;
    
    public List<T> getAll(T entity) throws Exception;
}

這個Dao定義了BaseSqlMapper中的方法,還提供了一個setMapperClass的方法。目的是在使用這個dao的時候,需要設置一個Mapper的class。且這個Mapper必須要是BaseSqlMapper或它的子類。所有的dao都可以用BaseMapperDao來完成CRUD操作即可,當BaseMapperDao的方法不夠用的情況下,可以在接口中提供SqlSession、SqlSessionTemplate方法,讓底層人員自己擴展所需要的方法。這裏的dao和mapper好像有點冗餘,因爲dao和mapper完成的功能都是類似或是相同的。但是你可以在dao中,同時調用不同的mapper,來完成當前模塊的dao所需要的功能。

11、 看看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<T> extends SqlSessionTemplate implements BaseMapperDao<T> {
    
    @Inject
    public BaseMapperDaoImpl(SqlSessionFactory sqlSessionFactory) {
        super(sqlSessionFactory);
    }
    
    private Class<? extends BaseSqlMapper> mapperClass;
    
    public void setMapperClass(Class<? extends BaseSqlMapper> mapperClass) {
        this.mapperClass = mapperClass;
    }
 
    public BaseSqlMapper<T> 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<T> 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。提供的setMapperClass方法需要設置其BaseSqlMapper或它的子類。

好了,至此基本的CRUD的mapper和dao就算完成了。現在我們可以定義我們自己的業務模塊,調用公共組件來完成增刪改查操作。

12、 下面測試下這個BaseMapperDao功能

package com.hoo.dao;
 
import javax.inject.Inject;
import org.junit.Before;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit38.AbstractJUnit38SpringContextTests;
import com.hoo.entity.Account;
import com.hoo.mapper.AccountMapper;
 
/**
 * function:
 * @author hoojo
 * @createDate 2011-4-14 下午01:08:49
 * @file BaseMapperDaoImplTest.java
 * @package com.hoo.dao
 * @project MyBatisForSpring
 * @blog http://blog.csdn.net/IBM_hoojo
 * @email [email protected]
 * @version 1.0
 */
@ContextConfiguration("classpath:applicationContext-*.xml")
public class BaseMapperDaoImplTest extends AbstractJUnit38SpringContextTests {
    
    @Inject
    private BaseMapperDao<Account> dao;
    
    @Before
    public void init() {
        System.out.println(dao);
        dao.setMapperClass(AccountMapper.class);
    }
    
    public void testGet() throws Exception {
        init();
        Account acc = new Account();
        acc.setAccountId(28);
        System.out.println(dao.get(acc));
    }
    
    public void testAdd() throws Exception {
        init();
        Account account = new Account();
        account.setUsername("temp@156.com");
        account.setPassword("abc");
        System.out.println(dao.add(account));
    }
}

13、 下面定義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<T> {
    
    /**
     * 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<T> getList() throws DataAccessException;
}

14、 AccountDao實現類

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.dao.BaseMapperDao;
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 AccountDaoImpl<T extends Account> implements AccountDao<T> {
    
    @Inject
    private BaseMapperDao<Account> dao;
    
    public boolean addAccount(T entity) throws DataAccessException {
        dao.setMapperClass(AccountMapper.class);
        boolean flag = false;
        try {
            dao.add(entity);
            flag = true;
        } catch (DataAccessException e) {
            flag = false;
            throw e;
        } catch (Exception e) {
            throw new RuntimeException(e); 
        }
        return flag;
    }
 
    public T getAccount(Integer id) throws DataAccessException {
        dao.setMapperClass(AccountMapper.class);
        Account acc = new Account();
        T entity = null;
        try {
            acc.setAccountId(id);
            entity  = (T) dao.get(acc);
        } catch (DataAccessException e) {
            throw e;
        } catch (Exception e) {
            throw new RuntimeException(e); 
        }
        return entity;
    }
 
    public List<T> getList() throws DataAccessException {
        dao.setMapperClass(AccountMapper.class);
        List<T> list = null;
        try {
            list = (List<T>) ((AccountMapper)dao.getMapper()).getAllAcount();
        } catch (DataAccessException e) {
            throw e;
        } catch (Exception e) {
            throw new RuntimeException(e); 
        }
        return list;
    }
}

注意,上面的方法都設置了MapperClass,表示當前dao的Mapper是AccountMapper對象。所有的mapper方法都是調用AccountMapper這個對象中的方法。

15、 下面定義服務器層接口

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<T> {
    /**
     * 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;
    
    public boolean execute(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<T> getList() throws DataAccessException;
}

16、 AccountBiz的實現代碼

package com.hoo.biz.impl;
 
import java.util.List;
import javax.inject.Inject;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Component;
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 AccountBizImpl<T extends Account> implements AccountBiz<T> {
    
    @Inject
    private AccountDao<T> 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<T> getList() throws DataAccessException {
        return dao.getList();
    }
 
    public boolean execute(T entity) throws DataAccessException {
        
        if (entity == null) {
            throw new BizException(Account.class.getName() + "對象參數信息爲Empty!");
        }
        return dao.addAccount(entity);
    }
}

直接注入AccountDao完成相關操作即可

17、 如果你需要在業務層設置事務傳播特性,需要在applicationContext-bean.xml中加入配置如下:

<-- 爲AccountBiz接口配置事務攔截器baseTransactionProxy是事務攔截器在Action中獲取這個對象 -->
<bean id="accountBiz" parent="baseTransactionProxy">
    <-- 設置target也就是AccountBiz的實現類 -->
    <property name="target" ref="accountBizImpl"/>
bean>

這樣在Action中注入accountBiz這個對象後,那麼當這個對象出現DataAccessException異常的時候,就會自動回滾事務。

至此,Spring和MyBatis的整合就完成了。

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