Spring学习笔记-Spring整合MyBatis

Spring 学习

Spring整合MyBatis

初步整合-回顾mybatis

步骤:

  1. 导入相关jar包

    • junit
    • mybatis
    • mysql数据库
    • spring相关
    • aop织入
    • mybatis-spring
    • lombok
    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</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.2.RELEASE</version>
        </dependency>
    
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.0.9.RELEASE</version>
        </dependency>
    
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.4</version>
        </dependency>
    
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.3</version>
        </dependency>
    
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
        </dependency>
        
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>
    
  2. 编写代码

注意:开启数据库,保证数据库能连上

  • 数据库连接的配置文件**db.properties**
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&useSSL=true
username=root
password=123456
  • mybatis核心配置文件**mybatis-config.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>
    
    <properties resource="db.properties"/>
    
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>

    <typeAliases>
        <package name="com.spring.pojo"/>
    </typeAliases>
    
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="com/spring/mapper/UserMapper.xml"/>
    </mappers>

</configuration>
  • 编写mybatis工具类**MyBatisUtil**
public class MyBatisUtil {

    private static SqlSessionFactory sqlSessionFactory = null;

    static {
        try {
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static SqlSession getSqlSession() {
        return sqlSessionFactory.openSession(true);
    }
}
  • 写实体类**User**
import lombok.Data;

@Data
public class User {
    private int id;
    private String name;
    private String pwd;
}
  • 写实体类对应的接口**UserMapper**
public interface UserMapper {
    List<User> selectUserAll();
}
  • 写接口的映射文件**UserMapper.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.spring.mapper.UserMapper">
    <select id="selectUserAll" resultType="user">
        select * from mybatis.user
    </select>
</mapper>
  • 写测试类**UserMapperTest**
public class UserMapperTest {
    @Test
    public void selectUserAllTest(){
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);

        List<User> users = mapper.selectUserAll();
        for (User user : users) {
            System.out.println(user);
        }

        sqlSession.close();
    }
}

【运行结果】
Spring学习笔记-Spring整合MyBatis

附目录结构:
Spring学习笔记-Spring整合MyBatis

更新整合

  1. 使用Spring的方式重新配置数据源连接数据库
<!--配置数据源dataSource
    使用Spring提供的数据源替换MyBatis的配置,也可以使用第三方的数据源,如c3p0,dbcp,druid等
    我们这里使用Spring提供的JDBC数据源:org.springframework.jdbc.datasource
-->
<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/mybatis?useUnicode=true&amp;characterEncoding=UTF-8&amp;serverTimezone=UTC&amp;useSSL=true"/>
    <property name="username" value="root"/>
    <property name="password" value="123456" />
</bean>
  1. 使用 SqlSessionFactoryBean 来创建SqlSessionFactory对象
<!--在MyBatis-Spring中,使用SqlSessionFactoryBean来创建sqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <!--绑定MyBatis核心配置文件-->
    <property name="configLocation" value="classpath:mybatis-config.xml"/>
    <!--mapperLocations属性用来指定MyBatis的映射器XML配置文件的位置-->
    <property name="mapperLocations" value="classpath*:com/spring/mapper/*.xml"/>
</bean>
  1. 使用SqlSessionTemplate来创建SqlSession对象
<!--SqlSessionTemplate:作为SqlSession的一个实现,可以使用它无缝代替你代码中已经在使用的SqlSession。-->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
    <!--只能使用构造器方式注入,因为SqlSessionTemplate没有set方法-->
    <!--使用SqlSessionFactory作为构造方法的参数来创建SqlSessionTemplate对象-->
    <constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>

【附】 1,2,3完整配置:spring-mapper.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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
     https://www.springframework.org/schema/beans/spring-beans.xsd">
 <!--配置数据源dataSource
     使用Spring提供的数据源替换MyBatis的配置,也可以使用第三方的数据源,如c3p0,dbcp,druid等
     我们这里使用Spring提供的JDBC数据源:org.springframework.jdbc.datasource
 -->
 <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/mybatis?useUnicode=true&amp;characterEncoding=UTF-8&amp;serverTimezone=UTC&amp;useSSL=true"/>
     <property name="username" value="root"/>
     <property name="password" value="123456" />
 </bean>

 <!--在MyBatis-Spring中,使用SqlSessionFactoryBean来创建sqlSessionFactory-->
 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
     <property name="dataSource" ref="dataSource" />
     <!--绑定MyBatis核心配置文件-->
     <property name="configLocation" value="classpath:mybatis-config.xml"/>
     <!--mapperLocations属性用来指定MyBatis的映射器XML配置文件的位置-->
     <property name="mapperLocations" value="classpath*:com/spring/mapper/*.xml"/>
 </bean>

 <!--SqlSessionTemplate:作为SqlSession的一个实现,可以使用它无缝代替你代码中已经在使用的SqlSession。-->
 <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
     <!--只能使用构造器方式注入,因为SqlSessionTemplate没有set方法-->
     <!--使用SqlSessionFactory作为构造方法的参数来创建SqlSessionTemplate对象-->
     <constructor-arg index="0" ref="sqlSessionFactory"/>
 </bean>
</beans>

到目前,相当于连接好了数据库,写好了工具类,可以得到sqlSession了。

  1. 实体类User.java,对应的接口UserMapper.java,及接口的映射文件UserMapper.xml不用变
@Data
public class User {
    private int id;
    private String name;
    private String pwd;
}
public interface UserMapper {
    List<User> selectUserAll();
}
<?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.spring.mapper.UserMapper">
    <select id="selectUserAll" resultType="user">
        select * from mybatis.user
    </select>
</mapper>

到目前为止,实体类,接口,SQL语句都已经写好了

  1. 新增接口实现类UserMapperImpl。【核心】
public class UserMapperImpl implements UserMapper {

    //MyBatis使用SqlSession,在MyBatis-Spring中改为SqlSessionTemplate替代
    private SqlSessionTemplate sqlSession;

    public void setSqlSession(SqlSessionTemplate sqlSession) {
        this.sqlSession = sqlSession;
    }

    public List<User> selectUserAll() {
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        return mapper.selectUserAll();
    }
}
  1. 在Spring中注册接口实现类UserMapperImpl。(applicationContext.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <import resource="spring-mapper.xml"/>

    <bean id="userMapperImpl" class="com.spring.mapper.UserMapperImpl">
        <property name="sqlSession" ref="sqlSession"/>
    </bean>

</beans>
  1. 测试

    完全按照Spring的方式写,不用关心MyBatis。sqlSession.getMapper(UserMapper.class)操作在接口实现类中实现,在测试类中是需要调用接口实现类的方法即可,并且,由于接口实现类在上面的步骤6中已经注册到Spring容器中,所以可以直接通过context.getBean()方法来得到,并调用其内的方法。不用实例化接口实现类。

public class UserMapperTest {
    @Test
    public void selectUserAllTest(){
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserMapper userMapper = context.getBean("userMapperImpl", UserMapper.class);
        for (User user : userMapper.selectUserAll()) {
            System.out.println(user);
        }
    }
}

【运行结果】
Spring学习笔记-Spring整合MyBatis

附目录结构:
Spring学习笔记-Spring整合MyBatis

更新整合2

通过SqlSessionDaoSupport的方式,不使用SqlSessionTemplate

  1. 新建UserMapperImpl2.java
/**
 * SqlSessionDaoSupport 是一个抽象的支持类,用来为你提供 SqlSession。
 * 调用 getSqlSession() 方法你会得到一个 SqlSessionTemplate,之后可以用于执行 SQL 方法.
 * 可以不用私有声明private SqlSessionTemplate sqlSession;
 */

public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper
{
    public List<User> selectUserAll() {
        return getSqlSession().getMapper(UserMapper.class).selectUserAll();
    }
}
  1. 将实现类注册到Spring容器中
<!--SqlSessionDaoSupport 需要通过属性设置一个 sqlSessionFactory-->
<bean id="userMapperImpl2" class="com.spring.mapper.UserMapperImpl2">
    <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
  1. 测试
@Test
public void selectUserAllTest2(){
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    UserMapper userMapper = context.getBean("userMapperImpl2", UserMapper.class);
    for (User user : userMapper.selectUserAll()) {
        System.out.println(user);
    }
}

【运行结果】
Spring学习笔记-Spring整合MyBatis

上一篇:mybatis延迟加载与缓存


下一篇:MybatisPlus的使用及增删改查