文章目录:

1.写在前面

2.实现步骤

2.1 项目的大体框架

2.2 使用Navicat在数据库中创建一张表student2

2.3 在pom.xml文件中加入maven依赖

2.4 编写实体类Student

2.5 编写StudentDao接口和对应的mapper映射文件

2.6 编写MyBatis主配置文件

2.7 编写service接口和相应的实现类(目的是通过service调用dao接口中的方法)

2.8 编写Spring配置文件

2.8.1 加载外部属性配置文件

2.8.2 声明数据源

2.8.3 注册SqlSessionFactoryBean

2.8.4 定义Mapper扫描配置器MapperScannerConfigurer

2.8.5 向Service中注入相关的接口名

2.9 编写测试方法

2.9.1 测试方法1

2.9.2 测试方法2

2.9.3 测试方法3

3.写在结尾


1.写在前面

将 MyBatis 与 Spring 进行整合,主要解决的问题就是将 SqlSessionFactory 对象交由 Spring 来管理。所以,该整合,只需要将 SqlSessionFactory 的对象生成器 SqlSessionFactoryBean 注册在 Spring 容器中,再将其注入给 Dao 的实现类即可完成整合。实现 Spring 与 MyBatis 的整合常用的方式:扫描的 Mapper 动态代理 Spring 像插线板一样,mybatis 框架是插头,可以容易的组合到一起。插线板 spring 插上 mybatis,两个框架就是一个整体。

使用mybatis,需要创建mybatis框架中的某些对象,使用这些对象,就可以使用mybatis提供的功能了。

对于mybatis执行sql语句,需要用到的对象有:

  1. SqlSessionFactory对象,只有创建了SqlSessionFactory对象,才能调用openSession()方法得到SqlSession对象。
  2. dao接口的代理对象,例如StudentDao接口,需要的代理对象为:SqlSeesion.getMapper(StudentDao.class)。
  3. 数据源DataSource对象,使用一个更强大、功能更多的连接池对象代替mybatis自己的PooledDataSource。


2.实现步骤

2.1 项目的大体框架

这里先给出spring整合mybatis之后,整个项目的架构图。

2.2 使用Navicat在数据库中创建一张表student2

其中 id 字段为主键,同时设置了自动增长。

2.3 在pom.xml文件中加入maven依赖

<!-- spring依赖 -->
<dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.2.5.RELEASE</version>
</dependency>
<!-- spring事务依赖 -->
<dependency><groupId>org.springframework</groupId><artifactId>spring-tx</artifactId><version>5.2.5.RELEASE</version>
</dependency>
<dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>5.2.5.RELEASE</version>
</dependency>
<!-- mybatis依赖 -->
<dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.1</version>
</dependency>
<!-- mybatis和spring集成依赖 -->
<dependency><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId><version>1.3.1</version>
</dependency>
<!-- mysql驱动 -->
<dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.9</version>
</dependency>
<!-- 阿里的连接池 -->
<dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.1.12</version>
</dependency>
<!-- 单元测试 -->
<dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.11</version><scope>test</scope>
</dependency>
<build><resources><resource><directory>src/main/java</directory> <!--所在的目录--><includes> <!--包括目录下的.properties,.xml 文件都会扫描到--><include>**/*.properties</include><include>**/*.xml</include></includes><filtering>false</filtering></resource></resources></build>

2.4 编写实体类Student

package com.bjpowernode.entity;/****/
public class Student {private Integer id;private String name;private Integer age;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}@Overridepublic String toString() {return "Student{" +"id=" + id +", name='" + name + '\'' +", age=" + age +'}';}
}

2.5 编写StudentDao接口和对应的mapper映射文件

package com.bjpowernode.dao;import com.bjpowernode.entity.Student;import java.util.List;/****/
public interface StudentDao {int insertStudent(Student student);List<Student> selectStudent();
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.bjpowernode.dao.StudentDao"><!-- 使用insert、update、delete、select标签编写sql语句 --><insert id="insertStudent">insert into student2(name,age) values(#{name},#{age})</insert><select id="selectStudent" resultType="com.bjpowernode.entity.Student">select id,name,age from student2</select></mapper>

2.6 编写MyBatis主配置文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><!-- 设置日志 --><settings><setting name="logImpl" value="STDOUT_LOGGING"/></settings><mappers>
<!--        <mapper resource="com/bjpowernode/dao/StudentDao.xml"/>--><!-- 将dao包下的所有mapper文件全部扫描 --><package name="com.bjpowernode.dao"/></mappers></configuration>

2.7 编写service接口和相应的实现类(目的是通过service调用dao接口中的方法)

package com.bjpowernode.service;import com.bjpowernode.entity.Student;import java.util.List;/****/
public interface StudentService {int addStudent(Student student);List<Student> queryStudent();
}
package com.bjpowernode.service.impl;import com.bjpowernode.dao.StudentDao;
import com.bjpowernode.entity.Student;
import com.bjpowernode.service.StudentService;import java.util.List;public class StudentServiceImpl implements StudentService {private StudentDao studentDao;public void setStudentDao(StudentDao studentDao) {this.studentDao = studentDao;}@Overridepublic int addStudent(Student student) {int rows=studentDao.insertStudent(student);return rows;}@Overridepublic List<Student> queryStudent() {List<Student> students=studentDao.selectStudent();return students;}
}

2.8 编写Spring配置文件

这里使用阿里的连接池、以及外部属性配置文件来读取数据库连接的相关信息。

先给出外部属性配置文件:jdbc.properties

jdbc.url=jdbc:mysql://localhost:3306/ssm?useUnicode=true&amp;characterEncoding=utf-8
jdbc.username=root
jdbc.password=12345678

2.8.1 加载外部属性配置文件

<!-- 加载外部属性配置文件 -->
<context:property-placeholder location="classpath:jdbc.properties"/>

2.8.2 声明数据源

<!-- 声明数据源DataSource -->
<bean id="myDataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"><property name="url" value="${jdbc.url}"/><property name="username" value="${jdbc.username}"/><property name="password" value="${jdbc.password}"/>
</bean>

2.8.3 注册SqlSessionFactoryBean

<!-- 声明SqlSessionFactoryBean,在这个类的内部,创建SqlSessionFactory对象,之后就可以获取SqlSession对象 -->
<bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean"><!-- 指定数据源 --><property name="dataSource" ref="myDataSource"/><!-- 指定mybatis主配置文件 --><property name="configLocation" value="classpath:mybatis.xml"/>
</bean>

2.8.4 定义Mapper扫描配置器MapperScannerConfigurer

<!-- 声明MapperScannerConfigurer -->
<!--MapperScannerConfigurer作用:循环basePackage所表示的包,把包中的每个接口都找到,调用SqlSession.getMapper(XXXDao.class)把每个dao接口都创建出对应的dao代理对象,将dao代理对象放在容器中对于StudentDao接口,其代理对象为 studentDao
-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><!-- 指定SqlSessionFactory对象的名称 --><property name="sqlSessionFactoryBeanName" value="factory"/><!-- 指定基本包,dao接口所在的包名 --><property name="basePackage" value="com.bjpowernode.dao"/>
</bean>

2.8.5 向Service中注入相关的接口名

<!-- 声明service -->
<bean id="studentService" class="com.bjpowernode.service.impl.StudentServiceImpl"><property name="studentDao" ref="studentDao"/>
</bean>

2.9 编写测试方法

2.9.1 测试方法1

    @Testpublic void test01() {String config="applicationContext.xml";ApplicationContext ctx=new ClassPathXmlApplicationContext(config);StudentDao studentDao= (StudentDao) ctx.getBean("studentDao");Student student=new Student();student.setName("李四");student.setAge(20);studentDao.insertStudent(student);}

2.9.2 测试方法2

    @Testpublic void test02() {String config="applicationContext.xml";ApplicationContext ctx=new ClassPathXmlApplicationContext(config);StudentService service= (StudentService) ctx.getBean("studentService");Student student=new Student();student.setName("张三");student.setAge(25);service.addStudent(student);}

2.9.3 测试方法3

    @Testpublic void test03() {String config="applicationContext.xml";ApplicationContext ctx=new ClassPathXmlApplicationContext(config);StudentService service= (StudentService) ctx.getBean("studentService");List<Student> students=service.queryStudent();for (Student stu : students) {System.out.println("stu = " + stu);}}


3.写在结尾

Spring整合MyBatis的总体步骤可以总结为以下几点:

Spring——Spring整合MyBatis相关推荐

  1. Spring Boot 教程(三): Spring Boot 整合Mybatis

    教程简介 本项目内容为Spring Boot教程样例.目的是通过学习本系列教程,读者可以从0到1掌握spring boot的知识,并且可以运用到项目中.如您觉得该项目对您有用,欢迎点击收藏和点赞按钮, ...

  2. spring boot 整合mybatis 无法输出sql的问题

    使用spring boot整合mybatis,测试功能的时候,遇到到了sql问题,想要从日志上看哪里错了,但是怎么都无法输出执行的sql,我使用的是log4j2,百度了一下,很多博客都说,加上下面的日 ...

  3. Spring boot 整合 Mybatis 实现增删改查(MyEclipse版)

    1.首先搭建好一个Spring boot 程序,编写好启动类. 启动类代码如下: @SpringBootApplication public class Start {public static vo ...

  4. spring boot整合mybatis+通用mapper+pagehelper分页插件

    spring boot整合mybatis+通用mapper+pagehelper分页插件 pom依赖 <?xml version="1.0" encoding="U ...

  5. spring boot整合mybatis步骤

    spring boot整合mybatis步骤 官方说明:MyBatis-Spring-Boot-Starter will help you use MyBatis with Spring Boot 其 ...

  6. Spring Boot整合MyBatis

    最近项目原因可能会继续开始使用MyBatis,已经习惯于spring-data的风格,再回头看xml的映射配置总觉得不是特别舒服,接口定义与映射离散在不同文件中,使得阅读起来并不是特别方便. Spri ...

  7. Spring Boot基础学习笔记06:Spring Boot整合MyBatis

    文章目录 零.学习目标 1.了解Spring Boot数据访问概述 2.掌握使用注解的方式整合MyBatis 3.掌握使用配置文件的方式整合MyBatis 一.Spring Boot数据访问概述 二. ...

  8. Spring Boot 整合MyBatis(23)

    Spring Boot 整合MyBatis Spring Boot 整合 Druid 引入依赖 配置 application.yml pring Boot 整合 tk.mybatis 引入依赖 配置 ...

  9. Spring Boot 整合 MyBatis Plus实现多数据源的两种方式

    第一种:使用配置类的方式: 项目结构 xml依赖: <?xml version="1.0" encoding="UTF-8"?> <proje ...

  10. 干货必看|Spring Boot整合MyBatis框架详解

    在开发中,我们通常会对数据库的数据进行操作,Sprirng Boot对关系型数据库和非关系型数据库的访问操作都提供了非常好的整合支持.所以今天壹哥就给大家讲解一下,如何在SpringBoot环境中整合 ...

最新文章

  1. Go语言int类型绑定方法
  2. vue实现移动端圆形旋钮插件
  3. 连分数求解Pell方程
  4. 联想微型计算机报价,联想电脑一体机报价
  5. 为什么操作dom会消耗性能
  6. Ant步步为营(4)ant启动tomcat
  7. 【codevs1037】取数游戏,博弈
  8. Grow heap (frag case) to 6.437MB for 1114126-byte allocation
  9. ETH基金会社区经理:以太坊改进流程EIP-1正在更新
  10. OpenVz Centos4 Oracle 10g VE
  11. mysql连17张表_mysql连表查询
  12. 《Modern Python Cookbook》(Python经典实例)笔记 1.13 使用元组
  13. QQ空间登录参数分析Firefox+Firebug
  14. 公告:软件测试就业课涨价调整暨教学服务升级通知
  15. 听听那冷雨 -- 余光中
  16. 如何制作千人千面的NFT?如何存储NFT?#Crystals #nft.storage #ipfs
  17. 算法编程10:岛屿的最大面积
  18. Typora+PicGo+Gitee
  19. 【C++】Lambda 表达式详解
  20. DSF学习1_Dubbo详解(一)分布式服务框架的概念理解

热门文章

  1. 有关500强企业大数据
  2. Activity启动模式singleInstance
  3. 科目二连续失败的反思
  4. 乳山金岭中学校计算机老师,乳山市金岭中学
  5. 强烈推荐免费在线图片转文字的工具
  6. ScreenToGIF工具分享--将视频转成GIF动图
  7. AUL恢复truncate删除的表
  8. python3.7 openpyxl 在excel单元格中写入数据
  9. 一文读懂有关Tree的前世今生
  10. HTML块级元素与行内元素的转变