1. 程式人生 > 其它 >ssm-spring整合mybatis

ssm-spring整合mybatis

ssm-spring整合mybatis

MyBatis-Spring簡介

MyBatis-Spring是一個依賴庫,可以無縫的將MyBatis整合到Spring中。該庫可以讓MyBatis參與到Spring事務管理中,可以負責mapper和SqlSession的建立和注入, 可以將MyBatis中的異常轉換為Spring的DataAccessException。最終讓你構建的工程程式碼脫離MyBatis,Spring和MyBatis-Spring的依賴。

快速開始

  1. 匯入依賴:
  2. 首先在pom.xml檔案中,匯入以下配置:
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>2.0.6</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>5.3.10</version>
    </dependency>
  3. 配置資料來源:
  4. <!--配置資料來源,可以是實現了javax.sql.DataSource介面的任意資料來源,這裡使用MysqlDataSource-->
    <bean id="dataSource" class="com.mysql.cj.jdbc.MysqlDataSource">
        <property name="url" value="jdbc:mysql://xxx"/>
        <property name="user" value="資料庫使用者名稱"/>
        <property name="password" value="資料庫密碼"/>
    </bean>
  5. 配置SqlSessionFactory:
  6. 在之前的mybatis中提到過,使用MybatisUtils工具類來封裝SqlSession相關物件的構建,而現在我們將在Spring application context中對這些物件進行配置注入。
    <!--1、SqlSessionFactoryBean:實現了介面org.springframework.beans.factory.FactoryBean-->
    <!--2、SqlSessionFactory:通過SqlSessionFactoryBean物件的getObject()方法來構建-->
    <!--3、dataSource和mapperLocations:getObject()方法中建立SqlSessionFactory物件的屬性-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="mapperLocations" value="classpath*:com/zx/demo/mybatis/**/*.xml"/>
    </bean>
  7. 配置Mapper:
  8. <!--1、MapperFactoryBean:實現了介面org.springframework.beans.factory.FactoryBean-->
    <!--2、StudentMapper:通過MapperFactoryBean物件的getObject()方法來構建-->
    <!--3、mapperInterface和sqlSessionFactory:getObject()方法中建立StudentMapper介面代理實現物件的屬性-->
    <bean id="exampleMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
        <property name="mapperInterface" value="com.zx.demo.mybatis.spring.mapper.StudentMapper"/>
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>
  9. 編寫測試:
  10. public class MybatisTest {
        @Test
        public void test() throws Exception {
            ApplicationContext context = new ClassPathXmlApplicationContext("spring-context.xml");
            StudentMapper mapper = (StudentMapper) context.getBean("exampleMapper");
            List<Map<Object, Object>> maps = mapper.queryAll();
            for (Map<Object, Object> map : maps) {
                for (Object o : map.keySet()) {
                    System.out.println(o.toString() + ":" + map.get(o));
                }
                System.out.println("===");
            }
        }
    }
    工程結構如下:

    現在執行測試結果如下:

更多

更多詳細進階配置,請參考官網