1. 程式人生 > >不需要怎麼修改配置的Mybatis整合Spring要點

不需要怎麼修改配置的Mybatis整合Spring要點

首先對於Mybatis的主配置檔案,只需要修改一處地方,將事務交給Spring管理,其它地方可以原封不動。 

<?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>
    <properties resource="jdbc.properties"></properties>

    <typeAliases>
        <package name="com.sunwii.mybatis.bean" />
    </typeAliases>

    <environments default="development">
        <environment id="development">
       <!--將事務交張Spring管理--> <transactionManager type="org.mybatis.spring.transaction.SpringManagedTransactionFactory" /> <dataSource type="POOLED"> <property name="driver" value="${driver}" /> <property name="url" value="${url}" /> <property name="username" value="${user}" /> <property name="password" value="${password}" /> </dataSource> </environment> </environments>
<!--這裡mappers塊可以保留或刪除或配置不存在的包也無所謂--> <mappers> <package name="Xcom/sunwii/mybatis/mapper"></package> </mappers> </configuration>

 

然後修改一下Mybatis工具類,重新命令為SqlSessionFactoryBuilder:

 

public class SessionFactoryBuilder {
    private String mybatisConfigPath;

    public String getMybatisConfigPath() {
        return mybatisConfigPath;
    }

    public void setMybatisConfigPath(String mybatisConfigPath) {
        this.mybatisConfigPath = mybatisConfigPath;
    }

    public SqlSessionFactory createSqlSessionFactory() {
        SqlSessionFactory factory = null;
        InputStream inputStream;
        try {
            inputStream = Resources.getResourceAsStream(this.mybatisConfigPath);
            factory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return factory;
    }
}

 

Spring的配置檔案也就比較簡潔:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:p="http://www.springframework.org/schema/p"
    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-4.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">


    <!-- 動態工廠例項化一個SqlSessionFactory -->
    <bean id="sessionFactoryBuilder" class="com.sunwii.mybatis.util.SessionFactoryBuilder">
        <property name="mybatisConfigPath" value="mybatis-config.xml" />
    </bean>
    <bean id="sessionFactory" factory-bean="sessionFactoryBuilder" factory-method="createSqlSessionFactory" />

    <!-- Mapper動態代理開發掃描 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.sunwii.mybatis.mapper" />
    </bean>
    
    
    <!-- 事務管理器 -->
    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource"
            value="#{sessionFactory.configuration.environment.dataSource}" />
    </bean>

    <!-- 註解事務 -->
    <tx:annotation-driven
        transaction-manager="transactionManager" />

    <!-- Service掃描 -->
    <context:component-scan
        base-package="com.sunwii.mybatis.service.impl" />



</beans>

關鍵點就在於:將 org.apache.ibatis.session.SqlSessionFactory  用Spring容器創建出來

有3種方式:

1.   mybatis.spring整合包的方式:正常來說可以直接配置 org.mybatis.spring.SqlSessionFactoryBean 來建立,但本例為了減少配置量,減少Mybatis的變動,以及簡潔起見,使用了自定義方式。

2.   自定義動態工廠方式:使用了自定義的動態工廠SessionFactoryBuilder(從單獨使用的Mybatis工具類中修改而來)方法來建立SqlSessionFactory。

      這樣的話,原先在Mybatis主配置裡配置的JDBC,資料來源之類的,不需移動到Spring中,而事務管理器中只需要引Spring表示式引用即可: #{sessionFactory.configuration.environment.dataSource}。

3.   自定義FactoryBean<SqlSessionFactory>介面方式:這就跟mybatis-spring.jar包整合的建立方式相類似(主要程式碼跟自定義動態工廠方法差不多,但需要實現好幾個FactoryBean的方法,程式碼稍多,為簡潔起見,不使用)

 

最後就是Service中直接使用Mapper介面了:

@Service
public class RoleServiceImpl implements RoleService {
    @Autowired 
    private RoleMapper roleMapper;
    @Autowired 
    private RolePermissionMapper rolePermissionMapper;
    @Autowired 
    private PermissionMapper permissionMapper;

    @Override
    @Transactional
    public int insertRole(Role role) {

        int rs = 0;

        rs = roleMapper.insert(role);

        //Permission permission = permissionMapper.selectById(56);
        //role.setPermissions(Arrays.asList(permission));
        
        Permission permission =  new Permission();
        permission.setName("permission-" + 1);
        permissionMapper.insert(permission);
        
        // 0 / 0  測試事務回滾
        new Integer(0 / 1);

        RolePermission rolePermission = new RolePermission();
        rolePermission.setRole(role);
        rolePermission.setPermission(permission);
        rolePermissionMapper.insert(rolePermission);

        return rs;
    }

    @Override
    public Role getRoleById(Integer id) {
        return roleMapper.selectById(id);
    }


}

 

說明:

由於採用了Mapper介面的方式來進行開發,org.mybatis.spring.mapper.MapperScannerConfigurer 在處理介面的時候,

經處理後的Mapper介面層用到了SqlSessionDaoSupport及SqlSessionTemplate,所以不需要擔心SqlSession執行緒安全問題,並且也不需要直接使用SqlSession,直接使用的是Mapper介面。

 

 

如果不採用Mapper介面開發,為了SqlSession執行緒安全問題,可以有幾種處理方式:

1。可以自定義ThreadLocal<SqlSession>,程式碼較多,事務管理麻煩,不推薦。上邊所有配置不變

2。讓daoImpl 實現SqlSessionDaoSupport並注入SqlSessionFactory就可以了。上邊所有配置不變

3。讓daoImpl 中注入SqlSessionTemplate就可以了。上邊所有配置不變,但多加一個SqlSessionTemplate的配置。

 

----------END OF 不需要怎麼修改配置的Mybatis整合Spring要點------------------ 

&n