Spring整合Mybatis方式一 - 常規整合 - 註冊對映器

御灵之灵發表於2024-03-27

前置工作

  • 導包(mybatis-spring、mysql-connector-java、mybatis、spring-webmvc等)

  • 實體類

  • DAO層兩個檔案(介面、xml檔案);Service層的介面

編寫Spring管理mybatis的xml-spring-dao.xml

核心程式碼(兩種方式實現)

第一種:xml

<!-- 將會話工廠物件託管給spring -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  <property name="dataSource" ref="dataSource" />
  <property name="mapperLocations" value="classpath:com/ylzl/mapper/BookMapper.xml"/>
</bean>

<!-- 註冊對映器:將對映器介面託管到Spring中 -->
<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
  <property name="sqlSessionFactory" ref="sqlSessionFactory" />
  <property name="mapperInterface" value="com.ylzl.mapper.UserMapper" />
</bean>
<!--    MapperFactoryBean物件 負責 SqlSession 的建立和關閉,
如果使用了 Spring 事務,當事務完成時,session 將會被提交或回滾。
最終任何異常都會被轉換成 Spring 的 DataAccessException 異常-->
<!--    mybatis對映器介面(如:interface UserMapper):sql部分可以使用mybatis的xml配置,與介面在同一路徑下,會被 MapperFactoryBean自動解析-->

第二種:annotation方式

點選檢視程式碼
@Bean
public SqlSessionFactory sqlSessionFactory() throws Exception {
  SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
  factoryBean.setDataSource(dataSource());
  return factoryBean.getObject();
}

@Bean
public MapperFactoryBean<UserMapper> userMapper() throws Exception {
    MapperFactoryBean<UserMapper> factoryBean = new MapperFactoryBean<>(UserMapper.class);
    factoryBean.setSqlSessionFactory(sqlSessionFactory());
    return factoryBean;
}

完整xml檔案

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">

    <context:annotation-config/>

<!--    使用Spring配置dataSource 相當於MyBatis配置檔案的<environments>-->
<!--    需要spring-jdbc包-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/ssmbuild"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </bean>

<!--    配置SqlSessionFactoryBean 等同於SqlSessionFactory
        做讀取資料來源以及註冊mapper.xml的工作-->
<!-- SqlSessionFactoryBean會呼叫類中的getObject()方法,返回SqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="mapperLocations" value="classpath:com/ylzl/mapper/BookMapper.xml"/>
    </bean>
<!--    獲得Mapper代理物件 等同於getMapper()-->
    <bean id="BookMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
        <property name="sqlSessionFactory" ref="sqlSessionFactory" />
        <property name="mapperInterface" value="com.ylzl.mapper.BookMapper" />
    </bean>

<!--    註冊employeeServiceImpl-->
    <bean id="bookServiceImpl" class="com.ylzl.service.impl.BookServiceImpl"/>
</beans>

重新編寫Service實現類

public class BookServiceImpl implements BookService{
    private BookMapper bookMapper;

    @Autowired //需要spring-aop包
    public BookServiceImpl(BookMapper bookMapper) {
        this.bookMapper = bookMapper;
    }

    @Override
    public Book getBookById(Integer bookID) {
        return bookMapper.getBookById(bookID);
    }
}

測試

ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
BookService bookServiceImpl = context.getBean("BookServiceImpl", BookService.class);
Book book = bookServiceImpl.getBookById(2);
System.out.println(book);

改進註冊對映器方式:使用發現對映器方式

MapperFactoryBean註冊對映器的最大問題,就是需要一個個註冊所有的對映器,而實際上mybatis-spring提供了掃描包下所有對映器介面的方法。

注意:以下兩種配置方法,均可替換上述MapperFactoryBean配置,而其餘程式碼與配置不變

方式一:配置掃描器標籤

1.與上面配置MapperFactoryBean不同,該配置無需注入SqlSessionFactory,它會自動匹配已有的會話工廠bean

2.如果配置了多個DataSource,也就是多個sqlSessionFactory時,可以使用factory-ref引數指定需要的會話工廠

<mybatis:scan base-package="com.ylzl.dao" factory-ref="sqlSessionFactory" />

<!-- annotation方式-註解配置類:
@MapperScan(basePackages = "com.ylzl.dao", sqlSessionFactoryRef = "sqlSessionFactory") -->
    
<!-- 省略其他... -->

方式二:MapperScannerConfigurer類

1.與上面標籤的功能差不多,同樣是掃描基準包,自動注入會話工廠

2.如果要更換注入的會話工廠,不同於常用的ref引入bean,而是使用value指定bean名,且屬性是sqlSessionFactoryBeanName

<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
     <property name="basePackage" value="com.ylyl.mapper" />
     <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>

annotation方式

@Bean
public MapperScannerConfigurer mapperScannerConfigurer() {
    MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
    mapperScannerConfigurer.setBasePackage("com.ylzl.dao");
    mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
    return mapperScannerConfigurer;
}

圖片:
p

相關文章