Mybatis學習筆記五:集成Spring

在上一章中,實現了關聯查詢,大概瞭解了Mybatis的基本用法,但在真正的項目中還是要跟Spring一起來用,本章主要說明Mybatis如何集成Spring

1、添加Spring配置文件

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

    <!-- 使用常見的c3p0數據連接池進行連接 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="user" value="root"/>
        <property name="password" value="zsfarther"/>
        <property name="jdbcUrl" value="jdbc:mysql://127.0.0.1:3306/mybatis-chapter1"/>
        <property name="driverClass" value="com.mysql.jdbc.Driver"/>
    </bean>

    <!-- 配置sessionfactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 指定數據源 -->
        <property name="dataSource" ref="dataSource"/>
        <!-- 指定mybatis配置文件 -->
        <property name="configLocation" value="mybatis-config.xml"/>
    </bean>

    <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
        <!-- 指定mapper -->
        <property name="mapperInterface" value="com.dfz.mybatis.mapper.UserMapper"/>
        <!-- 指定sessionfactory -->
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>
</beans>

從spring配置文件可以看出,mybatis集成spring主要做三件事情:
1)配置數據源;
2)配置sessionfactory;
3)指定mapper接口。

測試代碼如下,其餘代碼不做變更:

private ApplicationContext ctx;

    @Before
    public void before() {
        ctx = new ClassPathXmlApplicationContext("spring-config.xml");
    }

    @Test
    public void test() {
        System.out.println("------------查詢方法測試開始------------");
        UserMapper userMapper = (UserMapper) ctx.getBean("userMapper");
        System.out.println("------------測試查詢用戶------------");
        System.out.println(userMapper.selectUserByID(1));
        System.out.println("------------測試查詢用戶的文章------------");
        List<Article> articles = userMapper.getUserArticles(1);
        System.out.println(articles);
    }

輸出結果如下:
測試結果

2、總結

Mybatis集成Spring主要做三件事情,即將Mybatis的啓動,配置交給Spring管理,主要有:
1)配置數據源;
2)配置sessionfactory;
3)指定mapper接口。
未盡之處後期再補,代碼下載地址:https://github.com/EdwardEricZhang/MybatisFun

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章