Mybatis3详解(十五)----Mybatis简易整合Spring框架
1、前言
前面的十几篇文章都单独的总结了Mybatis在开发中的相关技术,但在实际开发中一般都是和Spring进行整合开发的,而Spring框架相信大家已经非常熟悉了,通过Spring的IOC/DI,能帮助我们完成对象的创建,对象之间的依赖,并且管理对象的声明周期,而Spring的AOP也能帮助我们管理对象的事务。所以下面我们来实现Mybatis和Spring的整合,并在整合后进行简单的测试。
2、创建maven项目
①、项目整体目录
②、导入依赖(双击快速复制)
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 | <!-- 添加Spring支持 --> < dependency > < groupId >org.springframework</ groupId > < artifactId >spring-core</ artifactId > < version >5.2.6.RELEASE</ version > </ dependency > < dependency > < groupId >org.springframework</ groupId > < artifactId >spring-beans</ artifactId > < version >5.2.6.RELEASE</ version > </ dependency > < dependency > < groupId >org.springframework</ groupId > < artifactId >spring-tx</ artifactId > < version >5.2.6.RELEASE</ version > </ dependency > < dependency > < groupId >org.springframework</ groupId > < artifactId >spring-context</ artifactId > < version >5.2.6.RELEASE</ version > </ dependency > < dependency > < groupId >org.springframework</ groupId > < artifactId >spring-aop</ artifactId > < version >5.2.6.RELEASE</ version > </ dependency > < dependency > < groupId >org.springframework</ groupId > < artifactId >spring-aspects</ artifactId > < version >5.2.6.RELEASE</ version > </ dependency > < dependency > < groupId >org.springframework</ groupId > < artifactId >spring-jdbc</ artifactId > < version >5.2.6.RELEASE</ version > </ dependency > <!-- Mybatis --> < dependency > < groupId >org.mybatis</ groupId > < artifactId >mybatis</ artifactId > < version >3.5.6</ version > </ dependency > <!-- Mybatis-Spring --> < dependency > < groupId >org.mybatis</ groupId > < artifactId >mybatis-spring</ artifactId > < version >2.0.3</ version > </ dependency > <!-- Mysql驱动 --> < dependency > < groupId >mysql</ groupId > < artifactId >mysql-connector-java</ artifactId > < version >8.0.21</ version > </ dependency > <!-- Druid数据库连接池 --> < dependency > < groupId >com.alibaba</ groupId > < artifactId >druid</ artifactId > < version >1.2.1</ version > </ dependency > <!-- 日志处理 --> < dependency > < groupId >log4j</ groupId > < artifactId >log4j</ artifactId > < version >1.2.17</ version > </ dependency > <!-- 单元测试 --> < dependency > < groupId >junit</ groupId > < artifactId >junit</ artifactId > < version >4.12</ version > </ dependency > |
3、编写实体类、Mapper接口以及Mapper.xml文件
①、User实体类
01 02 03 04 05 06 07 08 09 10 11 12 13 | /** * 用户实体类 */ public class User implements Serializable { private int userId; private String userName; private int userAge; private Date userBirthday; private int userSex; private String userAddress; //getter、setter、toString方法省略...... } |
②、UserMapper接口
01 02 03 04 05 06 07 | /** * UserMapper接口 */ public interface UserMapper { //查询所有用户信息 List<User> selectAllUser(); } |
③、UserMapper.xml文件
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 | <? 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="com.thr.mapper.UserMapper"> < resultMap id="userMap" type="com.thr.pojo.User"> < id property="userId" column="id"/> < result property="userName" column="username"/> < result property="userAge" column="age"/> < result property="userBirthday" column="birthday"/> < result property="userSex" column="sex"/> < result property="userAddress" column="address"/> </ resultMap > <!-- 查询所有用户 --> < select id="selectAllUser" resultMap="userMap"> select * from t_user </ select > </ mapper > |
5、编写数据库连接文件和日志文件
①、db.properties
01 02 03 04 05 | #数据库连接配置 database.driver=com.mysql.cj.jdbc.Driver database.url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8 database.username=root database.password=root |
②、log4j.properties
01 02 03 04 05 06 07 08 09 10 | log4j.rootLogger=DEBUG, Console #Console log4j.appender.Console=org.apache.log4j.ConsoleAppender log4j.appender.Console.layout=org.apache.log4j.PatternLayout log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n log4j.logger.java.sql.ResultSet=INFO log4j.logger.org.apache=INFO log4j.logger.java.sql.Connection=DEBUG log4j.logger.java.sql.Statement=DEBUG log4j.logger.java.sql.PreparedStatement=DEBUG |
6、编写Mybatis全局配置文件mybatis-config.xml
这里几乎没什么可配置的,都整合到Spring的配置文件中去了。
01 02 03 04 05 06 07 08 09 | <? 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 > </ configuration > |
7、编写Spring全局配置文件applicationContext.xml
在与Spring整合之前,我们都是在Mybatis的全局配置文件中管理数据源,并且sqlSessionFactory也是我们自己通过代码来完成注入的,但是现在与Spring整合了,这些操作都要交给Spring来管理了,所以下面我们来看一下applicationContext.xml 文件中的配置:
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | <? 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/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"> <!-- 加载classpath下的db.properties文件 --> < context:property-placeholder location="classpath:db.properties"/> <!-- 配置数据源 --> < bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> < property name="driverClassName" value="${database.driver}" /> < property name="url" value="${database.url}" /> < property name="username" value="${database.username}" /> < property name="password" value="${database.password}" /> </ bean > <!-- 配置sqlSessionFactory,SqlSessionFactoryBean是用来产生sqlSessionFactory的 --> < bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 加载上面配置好数据源 --> < property name="dataSource" ref="dataSource" /> <!-- 加载mybatis的映射配置文件;XxxMapper.xml --> < property name="mapperLocations" value="classpath:com/thr/mapper/*.xml" /> <!-- 加载mybatis的全局配置文件;mybatis-config.xml--> < property name="configLocation" value="classpath:mybatis-config.xml"/> <!-- 配置别名,使用包扫描,扫描com.thr.pojo包下的所有实体 --> < property name="typeAliasesPackage" value="com.thr.pojo"/> </ bean > <!-- 创建UserMapper接口的代理对象,这里是创建单个代理对象,不推荐这种方式,如果多个类就麻烦了 这里的org.mybatis.spring.mapper.MapperFactoryBean<T>类就是用来创建 Mapper代理对象的类 --> <!-- <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean"> <property name="mapperInterface" value="com.thr.mapper.UserMapper"/> <property name="sqlSessionFactory" ref="sqlSessionFactory"/> </bean> --> <!-- 加载所在包名下的Mapper接口,并且为其创建代理对象,推荐 --> < bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> < property name="basePackage" value="com.thr.mapper" /> <!-- 可选,如果不写,Spring启动时候。容器中自动会按照类型去把SqlSessionFactory对象注入进来 --> < property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></ property > </ bean > </ beans > |
8、编写测试代码与运行结果
①、测试代码
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | package com.thr.test; import com.thr.mapper.UserMapper; import com.thr.pojo.User; import org.junit.Before; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import java.util.List; public class UserMapperTest { //创建ApplicationContext容器 private ApplicationContext applicationContext = null ; @Before public void getApplicationContext() throws Exception { //获取Spring容器 applicationContext = new ClassPathXmlApplicationContext( "classpath:applicationContext.xml" ); } //查询所有用户 @Test public void testSelectAllUser(){ //获取UserMapper对象 UserMapper userMapper = applicationContext.getBean( "userMapper" , UserMapper. class ); List<User> users = userMapper.selectAllUser(); for (User user : users) { System.out.println(user); } } } |
②、运行结果
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· 因为Apifox不支持离线,我果断选择了Apipost!