JavaEE MyBatis與Spring的整合——基於mapper介面方式開發(教材學習筆記)
阿新 • • 發佈:2018-12-03
在MyBatis與Spring的整合開發中雖然可以通過傳統的DAO開發方式,但是採用DAO方式會產生大量的重複程式碼,因此學習另外一種程式設計方式就很重要了,即Mapper介面程式設計(本章程式碼是基於上一篇部落格的點這裡)
一、基於MapperFactoryBean的整合
MapperFactoryBean是Mapper-Spring團隊提供的一個用於根據Mapper介面生成Mapper物件的類,該類在Spring配置檔案中可以配置相關引數
1.在src目錄下,建立一個com.itheima.mapper包,然後在該包中建立CustomerMapper介面以及對應的對映檔案
package com.itheima.mapper; import com.itheima.po.Customer; public interface CustomerMapper { public Customer findCustomerById(Integer id); }
<?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="com.itheima.mapper.CustomerMapper"> <select id="findCustomerById" parameterType="Integer" resultType="Customer"> select * from t_customer where id=#{id} </select> </mapper>
2.MyBatis的配置檔案中,引入新的對映檔案
<mapper resource="com/itheima/mapper/CustomerMapper.xml"/>
3.在Spring的配置檔案中建立一個id為customerMapper的Bean,程式碼如下:
<bean id="customerMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"> <property name="mapperInterface" value="com.itheima.mapper.CustomerMapper"/> <property name="sqlSessionFactory" ref="sqlSessionFactory"/> </bean>
以上程式碼為MapperFactoryBean指定了介面及SqlSessionFactory
4.在測試類中編寫測試方法findCustomerByIdMapperTest()
@Test
public void findCustomerByIdMapperTest() {
ApplicationContext act= new ClassPathXmlApplicationContext("applicationContext.xml");
CustomerMapper customerMapper = act.getBean(CustomerMapper.class);
Customer customer = customerMapper.findCustomerById(1);
System.out.println(customer);
}
5.執行測試結果如下:
二、基於MapperScannerConfigurer的整合
在實際的專案中,DAO層會包含很多介面如果每個介面都像前面那樣在Spring配置檔案中配置,那麼不但會增加工作量也會使Spring配置檔案非常臃腫,為此MyBatis—Spring團隊提供了一種可以自動掃描的形式配置MyBatis中的對映器—採用MapperScannerConfigurer類
1.使用MapperScannerConfigurer非常簡單,只需要在Spring的配置檔案中編寫如下程式碼:
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.itheima.mapper"/>
</bean>
2.將上邊第二步和第三步的程式碼註釋掉,再次執行測試方法,結果如下: