9. Sping5整合MyBatis

文章目录

  • 项目结构
  • Mybatis层准备
    • 1. 导入pom依赖
    • 2. 编写com.kuang.pojo实体类User
    • 3. 在com.kuang.mapper包下,编写UserMapper接口、UserMapper.xml
    • 4. resources包下,编写mybatis-config.xml
  • Sping5整合MyBatis的步骤
    • 0. 需要导入mybatis-spring的pom依赖
    • 1. 引入Spring配置文件beans.xml
    • 2. 配置数据源ataSource,替换mybaits的数据源
    • 3. 配置SqlSessionFactory,关联MyBatis
    • 4. 注册sqlSessionTemplate,关联sqlSessionFactory;
    • 5. 增加UserMapper接口的实现类UserMapperImpl;私有化sqlSessionTemplate
    • 6. 还是在beans.xml中,注册bean实现
    • 7. 测试,并得到结果
  • 整合实现二:使用SqlSessionDaoSupport
    • 1. 整合实现二项目结构
    • 2. 修改一:编写UserMapperImpl2
    • 3. 修改二:修改beans.xml的配置
    • 4. 测试代码一样,进行测试

项目结构

9. Sping5整合MyBatis_第1张图片
所用数据库为2mybatis_first



Mybatis层准备

1. 导入pom依赖

    <properties>

        <maven.compiler.source>1.8maven.compiler.source>
        <maven.compiler.target>1.8maven.compiler.target>

        <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8project.reporting.outputEncoding>

        
        
        <junit.version>4.12junit.version>
        
        <lombok.version>1.18.10lombok.version>
        
        <jstl.version>1.2jstl.version>
        <standard.version>1.1.2standard.version>
        <servlet-api.version>2.5servlet-api.version>
        <jsp-api.version>2.0jsp-api.version>
        

    properties>


    <dependencies>
        
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>${junit.version}version>
        dependency>
        
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <version>${lombok.version}version>
        dependency>
        
        <dependency>
            <groupId>jstlgroupId>
            <artifactId>jstlartifactId>
            <version>${jstl.version}version>
        dependency>
        <dependency>
            <groupId>taglibsgroupId>
            <artifactId>standardartifactId>
            <version>${standard.version}version>
        dependency>
        <dependency>
            <groupId>javax.servletgroupId>
            <artifactId>servlet-apiartifactId>
            <version>${servlet-api.version}version>
            <scope>providedscope>
        dependency>
        <dependency>
            <groupId>javax.servletgroupId>
            <artifactId>jsp-apiartifactId>
            <version>${jsp-api.version}version>
            <scope>providedscope>
        dependency>
        

        
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatisartifactId>
            <version>3.5.4version>
        dependency>
        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>8.0.12version>
        dependency>
        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-webmvcartifactId>
            <version>5.1.10.RELEASEversion>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-jdbcartifactId>
            <version>5.1.10.RELEASEversion>
        dependency>
        <dependency>
            <groupId>org.aspectjgroupId>
            <artifactId>aspectjweaverartifactId>
            <version>1.9.4version>
        dependency>
        
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatis-springartifactId>
            <version>2.0.2version>
        dependency>
    dependencies>


    <build>
        <resources>
            <resource>
                <directory>src/main/javadirectory>
                <includes>
                    <include>**/*.propertiesinclude>
                    <include>**/*.xmlinclude>
                includes>
                <filtering>falsefiltering>
            resource>
            <resource>
                <directory>src/main/resourcesdirectory>
                <includes>
                    <include>**/*.propertiesinclude>
                    <include>**/*.xmlinclude>
                includes>
                <filtering>falsefiltering>
            resource>
        resources>
    build>

2. 编写com.kuang.pojo实体类User

@Data
public class User {
    private int id;  //id
    private String name;   //姓名
    private String pwd;   //密码
}

3. 在com.kuang.mapper包下,编写UserMapper接口、UserMapper.xml

UserMapper接口:

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

UserMapper.xml:
要注意namespace下的包名


DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.kuang.mapper.UserMapper">

    <select id="selectUser" resultType="com.kuang.pojo.User">
    select * from user
   select>

mapper>

4. resources包下,编写mybatis-config.xml


DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>




configuration>



Sping5整合MyBatis的步骤

0. 需要导入mybatis-spring的pom依赖

什么是 MyBatis-Spring?

MyBatis-Spring 会帮助你将 MyBatis 代码无缝地整合到 Spring 中。

知识基础

在开始使用 MyBatis-Spring 之前,你需要先熟悉 Spring 和 MyBatis 这两个框架和有关它们的术语。这很重要

MyBatis-Spring 需要以下版本:

MyBatis-Spring MyBatis Spring 框架 Spring Batch Java
2.0 3.5+ 5.0+ 4.0+ Java 8+
1.3 3.4+ 3.2.2+ 2.1+ Java 6+

<dependency>
   <groupId>org.mybatisgroupId>
   <artifactId>mybatis-springartifactId>
   <version>2.0.2version>
dependency>



1. 引入Spring配置文件beans.xml


<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
       http://www.springframework.org/schema/beans/spring-beans.xsd">

beans>



2. 配置数据源ataSource,替换mybaits的数据源

第三方数据源有:c3p0 dbcp druid

这里使用spring的数据源dataSource替换Mybatis的配置 【需要导入pom包:spring-jdbc】

<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/2mybatis_first?userSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC"/>
    <property name="username" value="root"/>
    <property name="password" value="xxxx"/>
bean>



3. 配置SqlSessionFactory,关联MyBatis

在 MyBatis-Spring 中,可使用SqlSessionFactoryBean来创建 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/kuang/mapper/*.xml"/>
    
bean>                



4. 注册sqlSessionTemplate,关联sqlSessionFactory;

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


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



5. 增加UserMapper接口的实现类UserMapperImpl;私有化sqlSessionTemplate

根据上一步,可知此时的sqlSessionTemplate相当于:在Mybatis上的已经在使用的 SqlSession

public class UserMapperImpl implements UserMapper {

    //sqlSession不用我们自己创建了,Spring来管理
    private SqlSessionTemplate sqlSession;

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

    public List<User> selectUser() {
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        return mapper.selectUser();
    }
}



6. 还是在beans.xml中,注册bean实现

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



7. 测试,并得到结果

 @Test
public void test2(){
    ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
    UserMapper mapper = (UserMapper) context.getBean("userMapper");
    List<User> user = mapper.selectUser();
    System.out.println(user);
}

结果成功输出!现在我们的Mybatis配置文件的状态!发现都可以被Spring整合!

在这里插入图片描述



整合实现二:使用SqlSessionDaoSupport

mybatis-spring1.2.3版以上的才有这个 。
SqlSessionDaoSupport是一个抽象的支持类,用来为你提供sqlsession。
调用getsqlsession()方法你会得到一个SglSessionTemplate,之后可以用于执行SQL方法

1. 整合实现二项目结构

9. Sping5整合MyBatis_第2张图片

2. 修改一:编写UserMapperImpl2

public class UserMapperImpl2  extends SqlSessionDaoSupport implements UserMapper {

    public List<User> selectUser() {
        UserMapper mapper = getSqlSession().getMapper(UserMapper.class);
        return mapper.selectUser();
    }

}

3. 修改二:修改beans.xml的配置

<bean id="userMapper" class="com.kuang.mapper.UserMapperImpl2">
     <property name="sqlSessionFactory" ref="sqlSessionFactory" />
bean>

4. 测试代码一样,进行测试

@Test
public void test2(){
   ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
   UserMapper mapper = (UserMapper) context.getBean("userDao");
   List<User> user = mapper.selectUser();
   System.out.println(user);
}

输出结果

在这里插入图片描述

总结 : 整合到spring以后可以完全不要mybatis的配置文件,除了这些方式可以实现整合之外,我们还可以使用注解来实现,这个等我们后面学习SpringBoot的时候还会测试整合!

你可能感兴趣的:(#,Spring5,spring)