Mybatis-Spring(整合)

Mybatis-Spring(整合)

1方式一:【SqlSessionTemplate】

1.1创建项目

利用maven搭建普通普通项目

1.2创建数据库

/*
 Navicat Premium Data Transfer

 Source Server         : test
 Source Server Type    : MySQL
 Source Server Version : 50527
 Source Host           : 127.0.0.1:3306
 Source Schema         : aini

 Target Server Type    : MySQL
 Target Server Version : 50527
 File Encoding         : 65001

 Date: 08/02/2021 12:48:08
*/

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for teacher
-- ----------------------------
DROP TABLE IF EXISTS `teacher`;
CREATE TABLE `teacher`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `pwd` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 6 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;

-- ----------------------------
-- Records of teacher
-- ----------------------------
INSERT INTO `teacher` VALUES (1, '武则天', '17772');
INSERT INTO `teacher` VALUES (5, '袁天罡', '12312');

SET FOREIGN_KEY_CHECKS = 1;

1.3导入相关依赖

 <dependencies>
        <!--mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.48</version>
        </dependency>
        <!--mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.3</version>
        </dependency>
        <!--spring-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.0.RELEASE</version>
        </dependency>
        <!--aspectj-->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.4</version>
        </dependency>
        <!--Spring操作数据库的话,还需要一个spring-jdbc-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.2.0.RELEASE</version>
        </dependency>
        <!--spring-mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.4</version>
        </dependency>
        <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.10</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/log4j/log4j -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
    </dependencies>

    <!--静态资源过滤问题-->
    <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>

1.4创建配置文件

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>
    <!--配置日志-->
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>
    <!--别名-->
    <typeAliases>
        <package name="cn.guxiang.pojo"/>
    </typeAliases>

    <!--注册映射器-->
    <mappers>
         <package name="cn.guxiang.mapper"/>
    </mappers>

</configuration>

springconfig.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">

    <!--注册bean-->

    <!--DataSource:使用Spring的数据源替换Mybatis的配置 c3p0 dbcp druid-->
    <!--使用Spring提供的JDBC:org.springframework.jdbc.datasource.DriverManagerDataSource-->
    <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/aini?useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
        <property name="username" value="root"/>
        <property name="password" value="1234"/>
    </bean>

    <!--SqlSessionFactory-->
    <bean id="sqlSessionFactory" 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/tian/mapper/UserMapper.xml"/>-->
    </bean>

    <!--SqlSessionTemplate=我们使用的SqlSession-->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <!--只能使用构造器注入,因为该类没有set方法-->
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>

    <bean id="teacherMapper" class="cn.guxiang.mapper.TeacherMapperImpl">
        <property name="sqlSession" ref="sqlSession"/>
    </bean>

</beans>

application.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="springconfig.xml"/>

    <bean id="teacherMapper" class="cn.guxiang.mapper.TeacherMapperImpl">
        <property name="sqlSession" ref="sqlSession"/>
    </bean>

</beans>

1.5创建类

创建实pojo包与mapper包

pojo包中创建教师类

package cn.guxiang.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Teacher {
    private Integer id;
    private String name;
    private String pwd;
}

mapper包中创建接口,接口实现类,xml

接口:TeacherMapper

package cn.guxiang.mapper;

import cn.guxiang.pojo.Teacher;

import java.util.List;
//查询方法
public interface TeacherMapper {
    List<Teacher> findAll();
}

xml:TeacherMapper.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="cn.guxiang.mapper.TeacherMapper">

<select id="findAll" resultType="Teacher">
    select *  from teacher
</select>
</mapper>

接口实现类:TeacherMapperImpl

package cn.guxiang.mapper;

import cn.guxiang.pojo.Teacher;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.mybatis.spring.SqlSessionTemplate;

import java.util.List;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class TeacherMapperImpl implements TeacherMapper{
    private SqlSessionTemplate sqlSession;


    @Override
    public List<Teacher> findAll() {
        TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
        return mapper.findAll();

    }

}

1.6测试

import cn.guxiang.mapper.TeacherMapper;
import cn.guxiang.pojo.Teacher;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

public class Demo01 {
    @Test
    public void demo01(){
        ApplicationContext context=new ClassPathXmlApplicationContext("application.xml");
        TeacherMapper teacherMapper = context.getBean("teacherMapper", TeacherMapper.class);
        List<Teacher> teachers = teacherMapper.findAll();
        for (Teacher teacher : teachers) {
            System.out.println(teacher);
        }
    }

}

2方式一:【SqlSessionTemplate】

2.1方法介绍

SqlSessionDaoSupport 是一个抽象的支持类,用来为你提供 SqlSession。调用 getSqlSession() 方法你会得到一个 SqlSessionTemplate,之后可以用于执行 SQL 方法,就像下面这样:

public class UserDaoImpl extends SqlSessionDaoSupport implements UserDao {
  public User getUser(String userId) {
    return getSqlSession().selectOne("org.mybatis.spring.sample.mapper.UserMapper.getUser", userId);
  }
}

在这个类里面,通常更倾向于使用 MapperFactoryBean,因为它不需要额外的代码。但是,如果你需要在 DAO 中做其它非 MyBatis 的工作或需要一个非抽象的实现类,那么这个类就很有用了。

SqlSessionDaoSupport 需要通过属性设置一个 sqlSessionFactory 或 SqlSessionTemplate。如果两个属性都被设置了,那么 SqlSessionFactory 将被忽略。

假设类 UserMapperImpl 是 SqlSessionDaoSupport 的子类,可以编写如下的 Spring 配置来执行设置:

<bean id="userDao" class="org.mybatis.spring.sample.dao.UserDaoImpl">
  <property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>

2.2创建项目

利用maven搭建普通普通项目

2.3创建数据库

/*
 Navicat Premium Data Transfer

 Source Server         : test
 Source Server Type    : MySQL
 Source Server Version : 50527
 Source Host           : 127.0.0.1:3306
 Source Schema         : aini

 Target Server Type    : MySQL
 Target Server Version : 50527
 File Encoding         : 65001

 Date: 08/02/2021 12:48:08
*/

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for teacher
-- ----------------------------
DROP TABLE IF EXISTS `teacher`;
CREATE TABLE `teacher`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `pwd` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 6 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;

-- ----------------------------
-- Records of teacher
-- ----------------------------
INSERT INTO `teacher` VALUES (1, '武则天', '17772');
INSERT INTO `teacher` VALUES (5, '袁天罡', '12312');

SET FOREIGN_KEY_CHECKS = 1;

2.4导入相关依赖

 <dependencies>
        <!--mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.48</version>
        </dependency>
        <!--mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.3</version>
        </dependency>
        <!--spring-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.0.RELEASE</version>
        </dependency>
        <!--aspectj-->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.4</version>
        </dependency>
        <!--Spring操作数据库的话,还需要一个spring-jdbc-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.2.0.RELEASE</version>
        </dependency>
        <!--spring-mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.4</version>
        </dependency>
        <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.10</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/log4j/log4j -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
    </dependencies>

    <!--静态资源过滤问题-->
    <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>

2.5创建配置文件

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>
    <!--配置日志-->
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>
    <!--别名-->
    <typeAliases>
        <package name="cn.guxiang.pojo"/>
    </typeAliases>

    <!--注册映射器-->
    <mappers>
         <package name="cn.guxiang.mapper"/>
    </mappers>

</configuration>

springconfig.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">

    <!--注册bean-->

    <!--DataSource:使用Spring的数据源替换Mybatis的配置 c3p0 dbcp druid-->
    <!--使用Spring提供的JDBC:org.springframework.jdbc.datasource.DriverManagerDataSource-->
    <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/aini?useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
        <property name="username" value="root"/>
        <property name="password" value="1234"/>
    </bean>

    <!--SqlSessionFactory-->
    <bean id="sqlSessionFactory" 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/tian/mapper/UserMapper.xml"/>-->
    </bean>

    <!--SqlSessionTemplate=我们使用的SqlSession-->
<!--    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">-->
<!--        &lt;!&ndash;只能使用构造器注入,因为该类没有set方法&ndash;&gt;-->
<!--        <constructor-arg index="0" ref="sqlSessionFactory"/>-->
<!--    </bean>-->

<!--    <bean id="teacherMapper" class="cn.guxiang.mapper.TeacherMapperImpl">-->
<!--        <property name="sqlSession" ref="sqlSession"/>-->
<!--    </bean>-->

    <!--方式二:SqlSessionDaoSupport-->
    <bean id="teacherMapper2" class="cn.guxiang.mapper.TeacherMapperImpl2">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>

</beans>

application.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="springconfig.xml"/>
    <!--方式一:-->
    <!--    <bean id="teacherMapper" class="cn.guxiang.mapper.TeacherMapperImpl">-->
    <!--        <property name="sqlSession" ref="sqlSession"/>-->
    <!--    </bean>-->

    <!--方式二:SqlSessionDaoSupport-->
    <bean id="teacherMapper2" class="cn.guxiang.mapper.TeacherMapperImpl2">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>

</beans>

1.5创建类

创建实pojo包与mapper包

pojo包中创建教师类

package cn.guxiang.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Teacher {
    private Integer id;
    private String name;
    private String pwd;
}

mapper包中创建接口,接口实现类,xml

接口:TeacherMapper

package cn.guxiang.mapper;

import cn.guxiang.pojo.Teacher;

import java.util.List;
//查询方法
public interface TeacherMapper {
    List<Teacher> findAll();
}

xml:TeacherMapper.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="cn.guxiang.mapper.TeacherMapper">

<select id="findAll" resultType="Teacher">
    select *  from teacher
</select>
</mapper>

接口实现类:TeacherMapperImpl2

package cn.guxiang.mapper;

import cn.guxiang.pojo.Teacher;
import org.mybatis.spring.support.SqlSessionDaoSupport;

import java.util.List;

public class TeacherMapperImpl2 extends SqlSessionDaoSupport implements TeacherMapper{
    @Override
    public List<Teacher> findAll() {
        return getSqlSession().getMapper(TeacherMapper.class).findAll();
    }
}

1.6测试

import cn.guxiang.mapper.TeacherMapper;
import cn.guxiang.pojo.Teacher;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

public class Demo01 {
    //方式一测试
    @Test
    public void demo01(){
        ApplicationContext context=new ClassPathXmlApplicationContext("application.xml");
        TeacherMapper teacherMapper = context.getBean("teacherMapper", TeacherMapper.class);
        List<Teacher> teachers = teacherMapper.findAll();
        for (Teacher teacher : teachers) {
            System.out.println(teacher);
        }
    }
    //方式二测试
    @Test //Spring整合Mybatis后
    public void demo02(){
        ApplicationContext context=new ClassPathXmlApplicationContext("application.xml");
        TeacherMapper teacherMapper2 = context.getBean("teacherMapper2", TeacherMapper.class);
        List<Teacher> teachers = teacherMapper2.findAll();
        for (Teacher teacher : teachers) {
            System.out.println(teacher);
        }
    }
}
上一篇:mybatis 一对多和多对一 简单案例笔记


下一篇:Mybatis知识小汇(9)——复杂查询环境搭建 (多对一处理)