Spring整合篇:Mybatis

265 阅读3分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第32天,点击查看活动详情

依赖

我们需要添加两个依赖:mybatis依赖是必须要加的,mybatis-spring是Spring整合Mybatis需要添加的依赖。

<dependencies>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.5</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>2.0.5</version>
    </dependency>
</dependencies>

接下去思考一下需要怎么去做?

  1. 这是数据层的技术整合,我们避免不了还需要添加连接数据库的依赖,这里以mysql为例。
  2. 正常Mybatis 是需要编写配置文件、编写映射接口Mapper、编写映射接口XML、在配置文件中标明接口XML,利用工厂类读取配置文件,这里就有几个重要的内容可以交给Spring管理了。

这种将核心交给Spring管理,即Spring对第三方技术的整合。那上面有:工厂类、接口这两个是可以交给Spring管理的。

数据源

我们正常操作数据库本身就需要配置数据源,此外Mybatis也需要指定数据源。

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.47</version>
</dependency>

编写配置类,配置数据源,数据源是DriverManagerDataSource

@Configuration
public class ApplicationConfig {
    @Bean
    public DriverManagerDataSource getDriverManagerDataSource(){
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/spring?characterEncoding=utf8");
        dataSource.setUsername("root");
        dataSource.setPassword("root");
        return dataSource;
    }

编写Mybatis的配置文件

可参考官网,尽管完全可以使用工厂类做配置,但是部分配置交给配置文件可以实现解耦。 这里我就选择配置了一下bean的扫描包的别名。在top.chengyunlai.bean中的类,在编写Mapper.xml的封装时可以以类名的小写直接写。

<?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>

    <typeAliases>
        <package name="top.chengyunlai.bean"/>
    </typeAliases>

</configuration>

容器中注册 工厂类

为什么需要管理工厂类可以看我这篇文章:快速上手Mybatis - 掘金 (juejin.cn)

mybatis中使用SqlSessionFactoryBuilder创建session工厂;
mybatis-spring整合时使用SqlSessionFactoryBean替代SqlSessionFactoryBuilder来创建session工厂。

@Bean("sqlSessionFactory")
public SqlSessionFactoryBean getSqlSessionFactoryBean(){
    SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
    sqlSessionFactoryBean.setDataSource(getDriverManagerDataSource());
    sqlSessionFactoryBean.setConfigLocation(new PathMatchingResourcePatternResolver().getResource("classpath:SqlMapConfig.xml"));
    return sqlSessionFactoryBean;
}

在工厂类中,我们通过setConfigLocation可以同时读取我们自己定义好的配置文件。

定义Mapper接口

Mapper接口也是需要被Spring管理的

public interface DepartmentMapper {
    void save(Department department);

    List<Department> findAll();
}

光写上这个Mapper接口还不行,需要有Mapper配置类与他绑定。 Mapper的配置类是写明Sql语言,Mapper配置类通过命名空间与接口绑定。

Mapper配置类

这里的Mapper配置类就是实现接口中定义的两个方法。可以通过插件的方式轻松完成该工作。由于编写Mapper的配置并不是这里讲的重点,所以有关内容还是看官方文档最好(有中文)

<?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="top.chengyunlai.mapper.DepartmentMapper">
    <insert id="save" parameterType="top.chengyunlai.bean.Department">
        insert into tbl_department (id, name, tel) values (#{id}, #{name}, #{tel});
    </insert>

    <select id="findAll" resultType="top.chengyunlai.bean.Department">
        select * from tbl_department;
    </select>
</mapper>

如何绑定Mapper配置类

因为绑定了Mapper配置,就表示完成了最后一步,想一下我们原先是如何做的?不使用Spring整合时,我们的做法是在总的配置类中实现的。也就是在Mapper的配置文件这一步,做Mapper映射器。 而在Spring中,我们需要MapperScannerConfigurer完成此工作。

在配置类中注入该类。

  • setBasePackage方法,传入mapper定义的包路径,可以将该包下所有的mapper接口进行实例化。这个就是相对于配置文件的包扫描。
  • setSqlSessionFactoryBeanName:需要指定我们自己定义的工厂类,所以我们该需要在工厂类上加上id。@Bean("sqlSessionFactory")
@Bean
public MapperScannerConfigurer mapperScannerConfigurer() {
    MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
    mapperScannerConfigurer.setBasePackage("top.chengyunlai.mapper");
    mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
    return mapperScannerConfigurer;
}