SpringBoot开发之整合Mybatis详解
作者:韩_师兄
这篇文章主要介绍了SpringBoot开发之整合Mybatis详解,MyBatis是一个半自动的ORM框架,它允许我们通过编写SQL语句来操作数据库,使用MyBatis,我们可以通过定义映射文件(XML文件)或使用注解的方式将Java对象与数据库表进行映射,需要的朋友可以参考下
1 整合Mybatis
Spring Boot官方的依赖包:
<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.4</version> </dependency>
1 配置模式
- 全局配置文件
- SqlSessionFactory: 自动配置好了
- SqlSession:自动配置了 SqlSessionTemplate 组合了SqlSession
- @Import(AutoConfiguredMapperScannerRegistrar.class)
- Mapper层: 只要写的操作MyBatis的接口带着了 @Mapper 就会被自动扫描进来
// MyBatis配置项绑定类。 @EnableConfigurationProperties(MybatisProperties.class) @AutoConfigureAfter({ DataSourceAutoConfiguration.class, MybatisLanguageDriverAutoConfiguration.class }) public class MybatisAutoConfiguration{} @ConfigurationProperties(prefix = "mybatis") public class MybatisProperties
配置修改mybatis:
# 配置mybatis规则 mybatis: config-location: classpath:mybatis/mybatis-config.xml # 全局配置文件位置 mapper-locations: classpath:mybatis/mapper/*.xml # sql映射文件位置 # Mapper接口--->绑定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="com.cf.admin.mapper.AccountMapper"> <!-- public Account getAcct(Long id); --> <select id="getAcct" resultType="com.cf.admin.bean.Account"> select * from t_user where id=#{id} </select> </mapper>
配置 private Configuration configuration; mybatis.configuration下面的所有,就是相当于改mybatis全局配置文件中的值
# 配置mybatis规则 mybatis: # config-location: classpath:mybatis/mybatis-config.xml mapper-locations: classpath:mybatis/mapper/*.xml configuration: map-underscore-to-camel-case: true # 可以不写全局;配置文件,所有全局配置文件的配置都放在configuration配置项中即可
使用流程:
- 导入mybatis官方starter
- 编写mapper接口。标准@Mapper注解
- 编写sql映射文件并绑定mapper接口
- 在application.yaml中指定Mapper配置文件的位置,以及指定全局配置文件的信息
2 注解模式
@Mapper public interface CityMapper { @Select("select * from t_user where id=#{id}") public User getById(Long id); }
3 混合模式
@Mapper public interface CityMapper { @Select("select * from t_user where id=#{id}") public User getById(Long id); }
使用流程:
- 引入mybatis-starter
- 配置application.yaml中,指定mapper-location位置即可
- 编写Mapper接口并标注@Mapper注解
- 简单方法直接注解方式 (如模式二)
- 复杂方法编写mapper.xml进行绑定映射
- @MapperScan(“com.cf.admin.mapper”) 简化,其他的接口就可以不用标注@Mapper注解
2 整合MyBatis-Plus
概述
MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
推荐安装 MybatisX 插件
使用
引入依赖
<dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.1</version> </dependency>
说明:
- MybatisPlusAutoConfiguration 配置类,MybatisPlusProperties 配置项绑定。
- SqlSessionFactory 自动配置好。底层是容器中默认的数据源
- mapperLocations 自动配置好。有默认值。
- **classpath*:/mapper/**/*.xml;任意包的类路径下的所有mapper文件夹下任意路径下的所有xml都是sql映射文件。 **
- 容器中也自动配置好了 SqlSessionTemplate
- @Mapper 标注的接口也会被自动扫描 也可直接 @MapperScan(“com.cf.admin.mapper”) 批量扫描就行
优点:
让Mapper继承 BaseMapper 就可以拥有简单crud的能力
到此这篇关于SpringBoot开发之整合Mybatis详解的文章就介绍到这了,更多相关SpringBoot整合Mybatis内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!