最新Spring整合MyBatis详解教程_mybatis-spring 使用详解-程序员宅基地

技术标签: spring  java  mybatis  SSM框架  MyBatis  Spring  


image-20200811201331833

mybatis-spring官方文档:http://mybatis.org/spring/zh/index.html

首先新建一个空的maven项目

1、导入相关jar包


1. junit

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.13</version>
    <scope>test</scope>
</dependency>

2. mybatis

<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.5</version>
</dependency>

3. mysql

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.21</version>
</dependency>

4. spring相关

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.2.8.RELEASE</version>
</dependency>
<!--Spring操作数据库,还需要spring-jdbc-->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>5.1.3.RELEASE</version>
</dependency>

5. aop织入

<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.4</version>
</dependency>

6. mybatis-spring

<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-spring</artifactId>
    <version>2.0.5</version>
</dependency>

7. lombok(选用)

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.12</version>
</dependency>

最后为了防止maven配置文件无法被导出或生效,加入以下代码

<!--在build中配置resources,防止我们资源导出失败的问题-->
<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、回顾:建立一个Mybatis程序

更详细过程可以看我之前的博客第一个MyBatis程序


1. IDEA连接数据库

大家连接自己的数据库即可,这里的实验表格为
image-20200811181559385


2. 编写MyBatis核心配置文件

image-20200811181900880
<?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/mybatis?useSSH=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="200024"/>
            </dataSource>
        </environment>
    </environments>
</configuration>

3. 创建数据库表对应实体类

image-20200811181927962
package pojo;

import lombok.Data;

@Data
public class User {
    
    private int id;
    private String name;
    private String pwd;
}

4. 编写Mapper接口

image-20200811182020272
package mapper;

import pojo.User;

import java.util.List;

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

5. 编写Mapper.xml配置文件

image-20200811182204453
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="mapper.UserMapper">
    <select id="getUser" resultType="pojo.User">
        select * from mybatis.user
    </select>
</mapper>

6. 编写测试类

image-20200811182242082
public class Test {
    
    @org.junit.Test
    public void test() throws IOException {
    
        String resource = "mybatis-config.xml";
        InputStream in = Resources.getResourceAsStream(resource);
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(in);
        SqlSession sqlSession = sessionFactory.openSession(true);
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> users = mapper.getUser();
        for (User user : users) {
    
            System.out.println(user);
        }
    }
}

7. 给Mapper.xml添加注册

在核心配置文件mybatis-config.xml中加入以下代码

<mappers>
    <mapper class="mapper.UserMapper"/>
</mappers>

8. 测试运行

image-20200811194703348

到此,mybatis程序的创建已成功,接下来将进行修改,整合spring



3、spring整合:方式一

通过SqlSessionTemplate创建SqlSession


接下来将在上述实验环境下进行修改

1. 引入spring配置文件

resource目录下新建spring-dao.xml
image-20200811183008850

<?xml version="1.0" encoding="UTF-8"?>
<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">

</beans>

2. 使用Spring的数据源替换MyBatis的数据源配置

spring配置文件中加入以下代码,配置数据源信息

<!--DataSource:使用Spring的数据源替换MyBatis的配置-->
<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?useSSH=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
    <property name="username" value="root"/>
    <property name="password" value="200024"/>
</bean>

此时,就可以删除mybatis核心配置文件mybatis-config.xml中的数据源配置
image-20200811184444369


3. 通过spring创建sqlSessionFactory

  • MyBatis 中,是通过 SqlSessionFactoryBuilder 来创建 SqlSessionFactory
  • 而在 MyBatis-Spring 中,则使用 SqlSessionFactoryBean 来创建

spring配置文件中加入以下代码,创建sqlSessionFactory

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

唯一的必要属性:用于 JDBC 的 DataSource,注入上述创建好的数据源

还可以配置其他属性,完全取代mybatis-config.xml中的配置
image-20200811185806672
这里加入两个属性配置

  • configLocation:指定mybatis的xml配置文件路径
  • mapperLocations:注册Mapper.xm映射器
<!--sqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <!--绑定mybatis配置文件-->
    <property name="configLocation" value="classpath:mybatis-config.xml"/>
    <!--注册Mapper.xm映射器-->
    <property name="mapperLocations" value="classpath:mapper/*.xml"/>
</bean>

这里,我们在spring配置文件中注册了Mapper.xml,就可以删除mybatis-config.xml中的Mapper.xml的注册
image-20200811185526572


4. 创建sqlSession对象

  • 在mybatis中,SqlSession 提供了在数据库执行 SQL 命令所需的所有方法

  • 而在spring-mybatis,没有SqlSession了,而是SqlSessionTemplate,这两个是同一个东西


spring配置文件中加入以下代码,创建sqlSession

  • 这里使用上述创建好的sqlSessionFactory 作为构造方法的参数来创建 SqlSessionTemplate 对象。
<!--SqlSessionTemplate:就是我们使用的sqlSession-->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
    <!--只能使用构造器进行注入,因为没有set方法-->
    <constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>

5. 新建接口实现类

上一步我们创建了sqlSession对象,此时需要创建一个类来使用sqlSession

image-20200811191543680

在该类中添加一个 SqlSession 属性,并添加 set方法 用于后续sqlSession的注入

public class UserMapperImpl implements UserMapper {
    
    //原来所有操作都通过SqlSession来执行,现在都是SqlSessionTemplate
    private SqlSessionTemplate sqlSession;

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

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

6. 创建实现类对象

利用spring创建上述接口实现类对象,取名为userMapper,并注入上述创建好的sqlSession对象

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

7. 修改测试类

此时,无需像先前一样创建sqlSessionFactory和sqlSession,我们只需获得创建好的实体类对象UserMapper,然后调用该对象的方法即可

public class Test {
    
    @org.junit.Test
    public void test() throws IOException {
    
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-dao.xml");
        UserMapperImpl userMapper = (UserMapperImpl) context.getBean("userMapper");
        List<User> users = userMapper.getUser();
        for (User user : users) {
    
            System.out.println(user);
        }
    }
}

8. 运行测试

image-20200811194703348

运行成功!!!



4、spring整合:方式二

通过SqlSessionDaoSupport获得Sqlsession


接下来将在上述实验环境下进行修改

1. 新建接口实现类

新建一个接口实现类,继承SqlSessionDaoSupport类,直接可以获得SqlSession对象
image-20200811205114097

public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper {
    
    public List<User> getUser() {
    
        SqlSession sqlSession = getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        return mapper.getUser();
    }
}

2. 创建接口实现类对象

通过Spring来创建

spring配置文件中创建上述实体类对象userMapper2,并设置sqlSessionFactory属性为上述创建好的sqlSessionFactory

<bean id="userMapper2" class="mapper.UserMapperImpl2">
    <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>

3. 修改测试类

同样,无需像先前一样创建sqlSessionFactory和sqlSession,我们只需获得创建好的实体类对象UserMapper2,然后调用该对象的方法即可

public class Test {
    
    @org.junit.Test
    public void test() throws IOException {
    
        ApplicationContext context = new ClassPathXmlApplicationContext("spring-dao.xml");
        UserMapperImpl2 userMapper = (UserMapperImpl2) context.getBean("userMapper2");
        List<User> users = userMapper.getUser();
        for (User user : users) {
    
            System.out.println(user);
        }
    }
}

4. 测试运行

image-20200811210202877

成功运行!!


THE END…

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_45173404/article/details/107945204

智能推荐

将本地镜像上传到Docker hub_本地docker镜像上传dockhub-程序员宅基地

文章浏览阅读2.4k次。一、准备工作1.注册账号注册一个Docker Hub账号,管理自己的镜像(共享镜像)https://hub.docker.com2.新建一个仓库Docker hub上面创建仓库,仓库用于存放镜像,就像我们在Github Create Create Repository比如:仓库名称叫navigation-server,所以路径就是liyinchi/navigation-server了。注意:仓库名称只能小写3.查看容器IDdocker ps上传到Doc._本地docker镜像上传dockhub

elementUI动态切换校验规则且切换校验规则时清空上一次校验产生的警告文字_ele 切换后清除校验-程序员宅基地

文章浏览阅读1.5k次,点赞2次,收藏8次。**this.$refs.transformerForm.clearValidate(['transformerLVSRateCapacity'])**清除切换校验时上一次校验留下的警告文字,<el-form :model="transfomerInfo" :rules="rules" ref="transformerForm" label-width="170px"> <el-form-item label="低压侧容量(MVA):" prop="transformer..._ele 切换后清除校验

vulhub靶场struts2漏洞复现_vulhub靶场有哪些漏洞-程序员宅基地

文章浏览阅读2k次。0x01、S2-001远程代码执行漏洞原理该漏洞因为用户提交表单数据并且验证失败时,后端会将用户之前提交的参数值使用 OGNL 表达式 %{value} 进行解析,然后重新填充到对应的表单数据中。例如注册或登录页面,提交失败后端一般会默认返回之前提交的数据,由于后端使用 %{value} 对提交的数据执行了一次 OGNL 表达式解析,所以可以直接构造 Payload 进行命令执行影响版本Struts 2.0.0 - Struts 2.0.8poc执行任意命令%{#a=(new java.lan_vulhub靶场有哪些漏洞

linux之找出两个文件里面相同的数据_limux中a-b相同内容-程序员宅基地

文章浏览阅读1.7w次,点赞5次,收藏33次。1 问题找出2个文件里面重复的数据(这个问题是csdn排名第一的大神stpeace的专栏在微信里面和我的交流,我当时一脸懵逼)文件a.txt文件内容如下cat a.txt123123234345456文件b.txt文件内容如下cat b.txt234345456789789两个文件重复的数据如下234345456..._limux中a-b相同内容

matlab绘制不同线性的直方图,Matlab绘制柱状图采用不同图案填充-程序员宅基地

文章浏览阅读545次。说明:在调用applyhatch前,按照自己的需要对Matlab自动绘制的图片编辑。function applyhatch(h,patterns,colorlist)%APPLYHATCH Apply hatched patterns to a figure% APPLYHATCH(H,PATTERNS) creates a new figure from the figure Hby% repl..._matlab不等间隔直方图

centos mysql navicat_centos7 安装 navicat for mysql-阿里云开发者社区-程序员宅基地

文章浏览阅读373次。本人使用的版本是navicat_for_mysql_10.0.11_cn_linux,使用官网上下的11版本的无法打开注意解压目录不要放在中文目录下,会出现各种问题,本人就出现打开之后添加列名添加不上。(1).先安装wine环境yum install wine如果yum源中没有,可以使用下面这个源wgethttp://download.fedoraproject.org/pub/epel/6/i..._centos7安装navicate for mysql

随便推点

使用Laravel值得关注的扩展包_laracasts/testdummy-程序员宅基地

文章浏览阅读1w次。下面会介绍一些laravel中一些好用的扩展包,当然,其中有的也是php的扩展包,合理的使用能够大大的提示开发效率。_laracasts/testdummy

列表类型python_Python列表类型-程序员宅基地

文章浏览阅读234次。列表的开始和结束要加上中括号 采用逗号将列表的项与项分开 使用“=”号操作符将整个列表赋予一个变量列表中可以放置任意的数据类型,如果是字符串,需要打上引号2.列表索引:从0开始;可以倒着来数,最后一个的序号是-1。取列表中的值:print aList[1]、print aList[-2]、print aList[-1][0]片段切片:[a:b],表示从a开始(包括a)到b之..._python列表类型怎么写

oracle临时表教程,在oracle存储过程中创建临时表-程序员宅基地

文章浏览阅读2.2k次。在oracle的存储过程中,不能直接使用DDL语句,比如create、alter、drop、truncate等。那如果我们想在存储过程中建立一张临时表就只能使用动态sql语句了:create or replace procedure pro asstr_sql varchar2(100);begin-- 创建临时表str_sql := 'create global temporary table ..._oracle 存储过程 临时表

centos 7 ffmpeg 批量 转码 mp4 kvm ts shell 懒人系列 -7_kvmts-程序员宅基地

文章浏览阅读476次。特别注意:本人很懒就搞了些懒人办法1.建立个文本。shell.sh,复制下面代码保存。打开终端(建议直接root用戶运行)。2.sudo chmod +x sheell.sh3.sudo ./shell.sh 文件名.avi (扩展名可以任意) 使用方法4.这段代码 支持H264 h265 支持60针视频5.shell.sh 文件要和视频文件同一目录6.转换完的文件被保存在finish文件夹中#!/bin/bash##i-合并视频##-change(转换)##i用法i(_kvmts

SpringBoot整合Redis与Cache实现分页缓存-程序员宅基地

文章浏览阅读4.2k次。SpringBoot整合Redis与Cache实现分页缓存_分页缓存

【FAQ】tomcat启动jdk版本不一致-程序员宅基地

文章浏览阅读192次。一、tomcat7.exe与startup.bat的区别:1、这两个都可以启动tomcat,但tomcat7.exe必须安装了服务才能启动,而startup.bat不需要2、另外一个区别是它们启动所使用的JAVA环境配置是分开的tomcat7.exe启动所使用JAVA配置与服务启动所使用的JAVA配置一样,都是通过tomcat7w.exe的JAVA面板配置(可以在创建服务前修..._龙蜥操作系统tomcat启动的java和java版本不一样

推荐文章

热门文章

相关标签