Version: Next

整合Mybatis

  1. 导入相关jar包
    • junit
    • Mybatis
    • Mysql数据库
    • Spring
    • Aop织入
    • Mybatis-Spring [new]
  2. 编写配置文件
  3. 测试

环境搭建

  • 新建Maven模块spring-10-mybatis

  • 导包

    <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.46</version>
    </dependency>
    <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.2</version>
    </dependency>
    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.2.0.RELEASE</version>
    </dependency>
    <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.1.9.RELEASE</version>
    </dependency>
    <dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>2.0.2</version>
    </dependency>

回忆Mybatis

  1. 编写实体类

  2. 编写核心配置文件

    <?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>
    <environments default="development">
    <environment id="development">
    <transactionManager type="JDBC"/>
    <dataSource type="POOLED">
    <property name="driver" value="com.mysql.jdbc.Driver"/>
    <property name="url" value="jdbc:mysql://localhost:3306/test?useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
    <property name="username" value="root"/>
    <property name="password" value="root"/>
    </dataSource>
    </environment>
    </environments>
    <mappers>
    <mapper resource="com/bsx/mapper/UserMapper.xml"/>
    </mappers>
    </configuration>
  1. 编写接口

    public interface UserMapper {
    public List<User> queryUser();
    }
  2. 编写Mapper.xml

    <?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.bsx.mapper.UserMapper">
    <select id="queryUser" resultType="com.bsx.pojo.User">
    SELECT * FROM USER;
    </select>
    </mapper>
  3. 解决找不到Mapper.xml文件的问题 在pom.xml中添加

    <build>
    <resources>
    <resource>
    <directory>src/main/resources</directory>
    <includes>
    <include>**/*.properties</include>
    <include>**/*.xml</include>
    </includes>
    <filtering>true</filtering>
    </resource>
    <resource>
    <directory>src/main/java</directory>
    <includes>
    <include>**/*.properties</include>
    <include>**/*.xml</include>
    </includes>
    <filtering>true</filtering>
    </resource>
    </resources>
    </build>
  4. 测试

    @Test
    public void testMybatis() throws IOException {
    InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    SqlSession sqlSession = sqlSessionFactory.openSession();
    try {
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    List<User> users = mapper.queryUser();
    for (User user : users) {
    System.out.println(user);
    }
    } catch (Exception e) {
    e.printStackTrace();
    } finally {
    sqlSession.close();
    }
    }

1. Spring整合Mybatis

1.1 Mybatis-Spring

什么是Mybatis-Spring

帮助将Mybatis代码无缝的整合到Spring中。它允许Mybatis参与到Spring的事务管理中,创建映射其Mapper和sqlSession并注入到bean中,以及将Mybatis的异常转换为Spring的DataAccessException。最终可以做到代码不依赖于Mybatis、Spring或Mybatis-Spring

1.1.1 导包

在环境搭建部分导过了

1.1.2 整合方式一 [重要]

  • Spring容器 -> 新建spring-dao.xml 注册以下东西

    • sqlSessionFactory (可以实现一切mybatis核心配置文件的功能)
      • 指定数据源DataSource
      • 绑定Mybatis配置文件
      • 绑定mapper.xml文件
    • DataSource
      • 使用Spring数据源替换Mybatis的配置 (还可用c3p0 druid) DriverManagerDataSource
      • 删除Mybatis核心配置文件中关于连接数据库的配置
    • SqlSessionTemplate (代替SqlSession)
      • 构造器注入,要求传入一个sqlSessionFactory
    <beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    https://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/aop
    https://www.springframework.org/schema/aop/spring-aop.xsd">
    <!-- DataSource 来自导入的包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/test?useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
    <property name="username" value="root"/>
    <property name="password" value="root"/>
    </bean>
    <!--sqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="datasource"/>
    <property name="configLocation" value="classpath:mybatis-config.xml"/>
    <property name="mapperLocations" value="classpath:com/bsx/mapper/*.xml"/>
    </bean>
    </beans>
  • Mapper实现类MapperImpl 所有操作使用sqlSessionTemplate来执行

    public class UserMapperImpl implements UserMapper{
    private SqlSessionTemplate sqlSession;
    //用来让Spring注入
    public void setSqlSession(SqlSessionTemplate sqlSession) {
    this.sqlSession = sqlSession;
    }
    public List<User> queryUser() {
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    List<User> users = mapper.queryUser();
    return users;
    }
    }

    把实现类注册到Spring容器

    <!-- DataSource 来自导入的包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/test?useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
    <property name="username" value="root"/>
    <property name="password" value="root"/>
    </bean>
    <!--sqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="datasource"/>
    <property name="configLocation" value="classpath:mybatis-config.xml"/>
    <property name="mapperLocations" value="classpath:com/bsx/mapper/*.xml"/>
    </bean>
    <!-- sqlSessionTemplate 构造器注入一个sqlSessionFactory-->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
    <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>
    <!-- userMapperImpl-->
    <bean id="userMapper" class="com.bsx.mapper.UserMapperImpl">
    <property name="sqlSession" ref="sqlSession"/>
    </bean>
    • 新建一个applicationContext.xml引入上面的spring-dao.xml
      <beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:aop="http://www.springframework.org/schema/aop"
      xsi:schemaLocation="http://www.springframework.org/schema/beans
      https://www.springframework.org/schema/beans/spring-beans.xsd
      http://www.springframework.org/schema/aop
      https://www.springframework.org/schema/aop/spring-aop.xsd">
      <import resource="spring-dao.xml"/>
      </beans>
  • 测试

    @Test
    public void testSpringMybatis(){
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
    List<User> users = userMapper.queryUser();
    for (User user : users) {
    System.out.println(user);
    }
    }

步骤

  1. 编写数据源配置
  2. 用sqlSessionFactoryBean 创建 sqlSessionFactory
  3. 创建sqlSessionTemplate
  4. 需要给mapper接口加实现类 [新]
  5. 将编写的实现类注册到Spring容器,提供set方法让spring注入
  6. 编写测试,直接从Spring容器拿Mapper实现类对象,调用方法

1.1.3 整合方式二

这种方式继承sqlSessionDaoSupport类,然后直接使用它的getSqlSession方法获得sqlSessionFactoryTemplate对象,这种方式不需要在Spring中注册一个sqlSessionFactoryTemplate

这种方式要求在将实现类注册到Spring容器时传入一个sqlSessionFactory对象,因为sqlSessionDaoSupport需要它来实例化sqlSessionTemplate

  • mapper实现类

    public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper {
    public List<User> queryUser() {
    return getSqlSession().getMapper(UserMapper.class).queryUser();
    }
    }
  • 注册到Spring

    <bean id="userMapper2" class="com.bsx.mapper.UserMapperImpl2">
    <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>
  • 测试

    @Test
    public void testSpringMybatis(){
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    UserMapper userMapper = context.getBean("userMapper2", UserMapper.class);
    List<User> users = userMapper.queryUser();
    for (User user : users) {
    System.out.println(user);
    }
    }