当前位置: 首页 > news >正文

Spring 整合mybatis

目录

1、梳理整合思路

2、整合实现

2.1 环境搭建

2.2 案例


1、梳理整合思路

  1. 将MyBatis的DataSource交给Spring IoC容器创建并管理,使用第三方数据库连接池(Druid,C3P0等)代替MyBatis内置的数据库连接池
  2. 将MyBatis的SqlSessionFactory交给Spring IoC容器创建并管理,使用spring-mybatis整合jar包中提供的SqlSessionFactoryBean类代替项目中的MyBatisUtil工具类
  3. 将MyBatis的接口代理方式生成的实现类,交给Spring IoC容器创建并管理

mybatis框架开发步骤

定义mapper接口,定义方法
定义mapper.xml映射文件
创建mybatis核心配置文件
创建SqlSession对象,使用该对象生成mapper接口的代理对象执行方法

spring整合mybatis的核心就是把mybatis开发用到的对象交由spring容器ioc来创建,这样就做到了整合的目的。
在开发中,我们一般不使用mybatis自带的数据源,而是使用别的数据源,比如c3p0,dbcp等,本人使用的是阿里的druid数据源。

2、整合实现

2.1 环境搭建

导入相关依赖:

<dependencies><!--单元测试--><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.11</version><scope>test</scope></dependency><!--spring核心ioc--><dependency><groupId>org.springframework</groupId><artifactId>spring-context</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></dependencies><build><!--目的是把src/main/java目录中的xml文件包含到输出结果中。输出到classes目录中--><resources><resource><directory>src/main/java</directory><!--所在的目录--><includes><!--包括目录下的.properties,.xml 文件都会扫描到--><include>**/*.properties</include><include>**/*.xml</include></includes><filtering>false</filtering></resource></resources><!--指定jdk的版本--><plugins><plugin><artifactId>maven-compiler-plugin</artifactId><version>3.1</version><configuration><source>1.8</source><target>1.8</target></configuration></plugin></plugins></build>

重点是注意resources标签的配置,很多人都是在这里出错导致程序运行报错找不到mapper.xml文件

2.2 案例

本案例从student表中查询学生和新增学生功能。

//实体类Student
public class Student {private int stuNo;private String stuName;private int cardID;private int classID;public Student() {}public Student(int stuNo, String stuName, int cardID, int classID) {this.stuNo = stuNo;this.stuName = stuName;this.cardID = cardID;this.classID = classID;}public int getStuNo() {return stuNo;}public void setStuNo(int stuNo) {this.stuNo = stuNo;}public String getStuName() {return stuName;}public void setStuName(String stuName) {this.stuName = stuName;}public int getCardID() {return cardID;}public void setCardID(int cardID) {this.cardID = cardID;}public int getClassID() {return classID;}public void setClassID(int classID) {this.classID = classID;}@Overridepublic String toString() {return "Student{" +"stuNo=" + stuNo +", stuName='" + stuName + '\'' +", cardID=" + cardID +", classID=" + classID +'}';}
}

mapper接口

public interface StudentMapper {//查询全部List<Student> queryAll();//新增学生void addStudent(Student student);
}

mapper.xml映射文件

<?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.mms.mapper.StudentMapper"><!--查询全部--><select id="queryAll" resultType="Student">select * from student</select><!--新增学生--><insert id="addStudent" parameterType="Student">insert into student (stuno,stuname,cardid,classid)values (#{stuNo},#{stuName},#{cardID},#{classID})</insert>
</mapper>

service接口

public interface IStudentService {List<Student> queryAll();void addStudent(Student student);
}

service实现类

public class StudentServiceImpl implements IStudentService {//mapper属性private StudentMapper mapper;//set注入给mapper对象赋值public void setMapper(StudentMapper mapper) {this.mapper = mapper;}@Overridepublic List<Student> queryAll() {return mapper.queryAll();}@Overridepublic void addStudent(Student student) {mapper.addStudent(student);}
}

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><typeAliases><!--批量设置别名,会自动的将该包下的所有类定义了别名,别名就是其自身且不区分大小--><package name="com.mms.entity" /></typeAliases><!--加载映射配置文件--><mappers><mapper resource="com/mms/mapper/studentMapper.xml"></mapper></mappers>
</configuration>

在这里由于数据源对象我们是交由spring容器托管了,因此mybatsi核心配置文件中就没有environments标签了。

spring配置文件

<?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:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"><!--加载数据库配置文件--><context:property-placeholder location="classpath:db.properties"/><!--声明数据源--><bean id="myDataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"><!--set注入给数据库信息赋值,不需要指定驱动类,sprinf根据url自动识别<property name="url" value="jdbc:mysql://localhost:3306/test?characterEncoding=utf8&amp;useSSL=true&amp;serverTimezone=UTC"/><property name="username" value="root"/><property name="password" value="333"/>--><!--使用db配置文件读取数据库信息,格式类似el表达式--><property name="url" value="${url}"/><property name="username" value="${username}"/><property name="password" value="${password}"/></bean><!--声明的是mybatis中提供的SqlSessionFactoryBean类,这个类内部创建SqlSessionFactory的--><bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><!--set注入赋值--><!--set注入,把数据库连接池付给了dataSource属性--><property name="dataSource" ref="myDataSource" /><!--mybatis主配置文件的位置configLocation属性是Resource类型,读取配置文件它的赋值,使用value,指定文件的路径,使用classpath:表示文件的位置--><property name="configLocation" value="classpath:mybatis-config.xml" /></bean><!--创建dao对象,使用SqlSession的getMapper(StudentDao.class)MapperScannerConfigurer:在内部调用getMapper()生成每个dao接口的代理对象。--><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><!--指定SqlSessionFactory对象的id--><property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /><!--指定包名, 包名是dao接口所在的包名。MapperScannerConfigurer会扫描这个包中的所有接口,把每个接口都执行一次getMapper()方法,得到每个接口的dao对象。创建好的dao对象放入到spring的容器中的。 dao对象的默认名称是 接口名首字母小写--><property name="basePackage" value="com.mms.mapper"/></bean><!--声明service--><bean id="studentServiceImpl" class="com.mms.service.impl.StudentServiceImpl"><property name="mapper" ref="studentMapper"/></bean>
</beans>

数据库配置文件

url = jdbc:mysql://localhost:3306/Xxx?characterEncoding=utf8&useSSL=true&serverTimezone=UTC
username = Xxx
password = Xxx

测试

    //执行查询全部,不使用service@Testpublic void test02() {String config = "applicationContext.xml";ApplicationContext ac = new ClassPathXmlApplicationContext(config);//获取mapper的代理对象StudentMapper mapper = (StudentMapper) ac.getBean("studentMapper");List<Student> students = mapper.queryAll();for (Student student : students) {System.out.println("student--->"+student);}}//执行增加学生,使用service@Testpublic void test03() {String config = "applicationContext.xml";ApplicationContext ac = new ClassPathXmlApplicationContext(config);//获取service对象IStudentService service = (IStudentService) ac.getBean("studentServiceImpl");Student student = new Student();student.setStuName("呵呵");student.setStuNo(1111);student.setCardID(1115);student.setClassID(1);service.addStudent(student);}

http://www.lryc.cn/news/309137.html

相关文章:

  • centos7升级openssl_3
  • nvidia a100-pcie-40gb环境安装
  • 嵌入式 Linux 下的 LVGL 移植
  • js同步和异步请求
  • 【Leetcode】2369. 检查数组是否存在有效划分
  • Laravel Octane 和 Swoole 协程的使用分析
  • 腾讯云又双叕降价,云服务器配置优惠价格表2024新版报价
  • 【react native】css踩坑记录
  • ChatGPT学习第四周
  • 2D割草/吸血鬼游戏 性能优化——GPU Spine动画
  • VSCode上搭建C/C++开发环境(vscode配置c/c++环境)Windows系统---保姆级教程
  • [渗透教程]-013-嗅探工具-wireshark操作
  • NLP Seq2Seq模型
  • 如何在 Linux 上使用 dmesg 命令
  • WPF的DataGrid设置标题头
  • 【软考】UML中的图之通信图
  • 为什么ChatGPT预训练能非常好地捕捉语言的普遍特征和模式
  • 如何安装ProtoBuf环境
  • C语言 vs Rust应该学习哪个?
  • IT廉连看——Uniapp——配置文件pages
  • 服务器上部署WEb服务方法
  • 设计模式:模版模式
  • pikachu之特殊注入之搜索型注入、xx型注入、insert/update注入、delete注入、宽字节注入
  • docker构建hyperf环境
  • WPF常用mvvm开源框架介绍 vue的mvvm设计模式鼻祖
  • HTML <script>元素的10个属性
  • NX二次开发:ListingWindow窗口的应用
  • 设计模式-结构型模式-外观模式
  • C++学习第四天(类与对象下)
  • 【AI Agent系列】【MetaGPT多智能体学习】0. 环境准备 - 升级MetaGPT 0.7.2版本及遇到的坑