一、前期准备

导入依赖

  1. <dependencies>
  2. <dependency>
  3. <groupId>junit</groupId>
  4. <artifactId>junit</artifactId>
  5. <version>4.12</version>
  6. </dependency>
  7. <dependency>
  8. <groupId>mysql</groupId>
  9. <artifactId>mysql-connector-java</artifactId>
  10. <version>8.0.11</version>
  11. </dependency>
  12. <dependency>
  13. <groupId>org.mybatis</groupId>
  14. <artifactId>mybatis</artifactId>
  15. <version>3.5.2</version>
  16. </dependency>
  17. <!--Spring、MyBatis整合包-->
  18. <dependency>
  19. <groupId>org.mybatis</groupId>
  20. <artifactId>mybatis-spring</artifactId>
  21. <version>2.0.2</version>
  22. </dependency>
  23. <!--Spring相关-->
  24. <dependency>
  25. <groupId>org.springframework</groupId>
  26. <artifactId>spring-jdbc</artifactId>
  27. <version>5.1.10.RELEASE</version>
  28. </dependency>
  29. <dependency>
  30. <groupId>org.springframework</groupId>
  31. <artifactId>spring-webmvc</artifactId>
  32. <version>5.1.10.RELEASE</version>
  33. </dependency>
  34. <dependency>
  35. <groupId>org.aspectj</groupId>
  36. <artifactId>aspectjweaver</artifactId>
  37. <version>1.9.4</version>
  38. </dependency>
  39. </dependencies>

Maven静态资源过滤问题

<!-- Maven由于“约定大于配置”,我们之后可能会遇到写的配置文件无法被导出或者生效的问题,解决方案如下: -->
<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>

回顾MyBatis

编写pojo实体类

package com.comprehensive.pojo;

public class User {
    private int id;
    private String name;
    private String pwd;

    public User() {}

    public User(int id, String name, String pwd) {
        this.id = id;
        this.name = name;
        this.pwd = pwd;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", pwd='" + pwd + '\'' +
                '}';
    }
}

编写mybatis配置文件

<?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.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&amp;useUnicode=true&amp;characterEncoding=utf-8&amp;characterSetResults=utf-8&amp;useSSL=false&amp;verifyServerCertificate=false&amp;autoReconnect=true&amp;autoReconnectForPools=true&amp;allowMultiQueries=true"/>
                <property name="username" value="root"/>
                <property name="password" value="txq199807031578"/>
            </dataSource>
        </environment>
    </environments>

    <!-- 绑定接口 -->
    <mappers>
        <mapper class="com.comprehensive.dao.UserMapper"></mapper>
    </mappers>

</configuration>

编写UserMapper接口

package com.comprehensive.dao;

import com.comprehensive.pojo.User;

import java.util.List;

public interface UserMapper {
    List<User> getAllUsers();
}

编写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="com.comprehensive.dao.UserMapper">
    <select id="getAllUsers" resultType="com.comprehensive.pojo.User">
        select * from mybatis.user;
    </select>
</mapper>

测试

package com.comprehensive.dao;

import com.comprehensive.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;

public class UserMapper_Test {
    @Test
    public void test1() {
        try {
            String resources = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resources);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            SqlSession sqlSession = sqlSessionFactory.openSession();

            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            for(User user : mapper.getAllUsers()) System.out.println(user);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

image.png

二、mybatis-spring

image.png
整合MyBatis之前需要了解mybatis-spring包中的一些重要类

SqlSessionFactoryBean

在 mybatis-spring 中,可使用SqlSessionFactoryBean来创建 SqlSessionFactory。要配置这个工厂 bean,只需要把下面代码放在 Spring 的 XML 配置文件中

<!--SqlSessionFactoryBean-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  <property name="dataSource" ref="dataSource"/>
</bean>

image.png
注意:SqlSessionFactory需要一个 DataSource(数据源)。这可以是任意的 DataSource,只需要和配置其它 Spring 数据库连接一样配置它就可以了。
在基础的 MyBatis 用法中,是通过 SqlSessionFactoryBuilder 来创建 SqlSessionFactory 的。而在 myBatis-spring 中,则使用 SqlSessionFactoryBean 来创建

SqlSessionTemplate

SqlSessionTemplate 是 myBatis-spring 的核心。作为 SqlSession 的一个实现,这意味着可以使用它无缝代替你代码中已经在使用的 SqlSession

<!--SqlSessionTemplate-->
<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
  <constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>

image.png
注意:可以使用 SqlSessionFactory 作为构造方法的参数来创建 SqlSessionTemplate 对象。
SqlSessionTemplate 可以参与到 Spring 的事务管理中,并且由于其是线程安全的,可以供多个映射器类使用,你应该总是用 SqlSessionTemplate 来替换 MyBatis 默认的 DefaultSqlSession 实现。在同一应用程序中的不同类之间混杂使用可能会引起数据一致性的问题。

三、整合MyBatis

方式一

image.png

配置数据源

<!--DataSource-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
  <property name="url" value="jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&amp;useUnicode=true&amp;characterEncoding=utf-8&amp;characterSetResults=utf-8&amp;useSSL=false&amp;verifyServerCertificate=false&amp;autoReconnect=true&amp;autoReconnectForPools=true&amp;allowMultiQueries=true"/>
  <property name="username" value="root"/>
  <property name="password" value="txq199807031578"/>
</bean>

配置SqlSessionFactory,关联MyBatis

<!--SqlSessionFactoryBean-->
<bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
  <property name="dataSource" ref="dataSource"/>
  <!--关联MyBatis-->
  <!--<property name="configLocation" value="classpath:mybatis-config.xml"/>-->
  <property name="mapperLocations" value="classpath:com/comprehensive/dao/UserMapper.xml"/>
  <!--
  <property name="mapperLocations" value="classpath*:com/comprehensive/dao/*.xml"/>
  -->
</bean>

注意:配置SqlSessionFactory后,mybatis-config.xml配置文件中对应的配置信息也可以省略
image.png

配置SqlSession,关联SqlSessionFactory

<!--SqlSessionTemplate-->
<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
  <!--关联SqlSessionFactory-->
  <constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>

编写Dao接口的实现类,私有化sqlSessionTemplate

package com.comprehensive.dao;

import com.comprehensive.pojo.User;
import org.mybatis.spring.SqlSessionTemplate;

import java.util.List;

public class UserDaoImpl implements UserMapper {

    private SqlSessionTemplate sqlSessionTemplate;

    public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
        this.sqlSessionTemplate = sqlSessionTemplate;
    }

    @Override
    public List<User> getAllUsers() {
        UserMapper mapper = sqlSessionTemplate.getMapper(UserMapper.class);
        return mapper.getAllUsers();
    }
}

注册bean实现

<!--DaoImpl-->
<bean id="userDaoImpl" class="com.comprehensive.dao.UserDaoImpl">
  <property name="sqlSessionTemplate" ref="sqlSessionTemplate"/>
</bean>

测试

public class UserMapper_Test {
    @Test
    public void test2() {
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        UserMapper userMapper = (UserMapper) context.getBean("userDaoImpl");
        for(User user : userMapper.getAllUsers()) System.out.println(user);
    }
}

image.png

方式二

image.png

配置数据源

<!--DataSource-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
  <property name="url" value="jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&amp;useUnicode=true&amp;characterEncoding=utf-8&amp;characterSetResults=utf-8&amp;useSSL=false&amp;verifyServerCertificate=false&amp;autoReconnect=true&amp;autoReconnectForPools=true&amp;allowMultiQueries=true"/>
  <property name="username" value="root"/>
  <property name="password" value="txq199807031578"/>
</bean>

配置SqlSessionFactory,关联MyBatis

<!--SqlSessionFactoryBean-->
<bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
  <property name="dataSource" ref="dataSource"/>
  <property name="mapperLocations" value="classpath*:com/comprehensive/dao/*.xml"/>
</bean>

编写Dao接口的实现类,继承SqlSessionDaoSupport类

package com.comprehensive.dao;

import com.comprehensive.pojo.User;
import org.mybatis.spring.support.SqlSessionDaoSupport;

import java.util.List;

public class UserDaoImpl2 extends SqlSessionDaoSupport implements UserMapper {
    @Override
    public List<User> getAllUsers() {
        return getSqlSession().getMapper(UserMapper.class).getAllUsers();
    }
}

注册bean实现

<!--DaoImpl-->
<bean id="userDaoImpl" class="com.comprehensive.dao.UserDaoImpl2">
  <property name="sqlSessionFactory" ref="sqlSessionFactoryBean"/>
</bean>

测试

public class UserMapper_Test {
    @Test
    public void test3() {
        ApplicationContext context = new ClassPathXmlApplicationContext("beans2.xml");
        UserMapper userMapper = context.getBean("userDaoImpl", UserMapper.class);
        for(User user : userMapper.getAllUsers()) System.out.println(user);
    }
}

image.png