文章目录
- 基于boot-starter方式
- 基于Bean方式
基于boot-starter方式
1、【microboot项目】修改配置文件,引入所需要的相关依赖库:
dependences.gradle
ext.versions = [ // 定义所有要使用的版本号springboot : '2.4.3', // SpringBoot版本号junit : '5.7.1', // 配置JUnit测试工具的版本编号junitPlatformLauncher : '1.7.1', // JUnit测试工具运行平台版本编号lombok : '1.18.18', // Lombok插件对应的版本号mysql : '8.0.25', // MySQL驱动的版本druid : '1.2.6', // Druid版本mybatisplus : '3.4.3', // Mybatis-plus-SpringBoot整合依赖
]
ext.libraries = [ // 定义所有的依赖库'spring-boot-gradle-plugin': "org.springframework.boot:spring-boot-gradle-plugin:${versions.springboot}",// 以下的配置为与项目用例测试有关的依赖'junit-jupiter-api': "org.junit.jupiter:junit-jupiter-api:${versions.junit}",'junit-vintage-engine': "org.junit.vintage:junit-vintage-engine:${versions.junit}",'junit-jupiter-engine': "org.junit.jupiter:junit-jupiter-engine:${versions.junit}",'junit-platform-launcher': "org.junit.platform:junit-platform-launcher:${versions.junitPlatformLauncher}",'junit-bom': "org.junit:junit-bom:${versions.junit}",// 以下的配置为Lombok组件有关的依赖'lombok': "org.projectlombok:lombok:${versions.lombok}",// 以下的配置为数据库开发所需要的依赖:'mysql-connector-java': "mysql:mysql-connector-java:${versions.mysql}",'druid-spring-boot-starter': "com.alibaba:druid-spring-boot-starter:${versions.druid}",'spring-jdbc': "org.springframework:spring-jdbc:${versions.springJdbc}",'druid': "com.alibaba:druid:${versions.druid}",// 以下的配置为MyBatis开发框架所需要的依赖:'mybatis-plus-boot-starter': "com.baomidou:mybatis-plus-boot-starter:${versions.mybatisPlus}",
]
build.gradle
project('microboot-database') { // 子模块dependencies { // 配置子模块依赖compile(project(':microboot-common')) // 引入其他子模块compile(libraries.'mysql-connector-java')compile(libraries.'druid') // 添加原始依赖compile(libraries.'mybatis-plus-boot-starter')}
}
2、【microboot-database子模块】application.yml
spring:datasource:type: com.alibaba.druid.pool.DruidDataSource # 配置数据源的类型driver-class-name: com.mysql.cj.jdbc.Driver # MySQL8之后的驱动url: jdbc:mysql://localhost:3306/yootk # 数据库的JDBC连接地址username: root # 用户名password: mysqladmin # 密码druid: # 定义数据库连接池所需要的相关配置项initial-size: 5 # 初始化连接池大小min-idle: 10 # 最小维持的连接池大小max-active: 50 # 最大可提供的连接数量max-wait: 60000 # 最长等待时间time-between-eviction-runs-millis: 6000 # 关闭空闲连接间隔(毫秒)min-evictable-idle-time-millis: 30000 # 连接最小的生存时间validation-query: SELECT 1 FROM dual # 数据库的状态检测test-while-idle: true # 判断连接是否可用test-on-borrow: false # 在获得连接之前是否要进行测试test-on-return: false # 归还连接前是否需要进行测试pool-prepared-statements: false # 不缓存PSTMTmax-pool-prepared-statement-per-connection-size: 20 # 配置PSTMT缓存个数mybatis-plus:config-location: classpath:META-INF/mybatis/mybatis.cfg.xml # mybatis配置文件所在路径type-aliases-package: com.yootk.vo # 定义所有操作类的别名所在包mapper-locations: classpath:META-INF/mybatis/mapper/**/*.xml # 所有的mapper映射文件global-config: # 全局配置db-config: //logic-not-delete-value: 0 # 数据删除前logic-delete-value: 1 # 数据删除后
此时在member表中存在有一个isdel字段,那么这个字段的内容就是逻辑删除项,如果是O(false)表示未删除,如果是1 (true)表示删除操作。
3、【microboot-database子模块】修改 Member程序类,追加逻辑删除的配置项:
package com.yootk.vo;import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableLogic;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;import java.util.Date;@Data
@TableName("member") // 定义该VO类对应的数据表名称
public class Member {@TableId // 配置主键列private String mid;private String name;private Integer age;private Double salary;private Date birthday;private String content;@TableLogic // 逻辑删除处理private Integer isdel; // 逻辑删除字段
}
4、【microboot-database子模块】创建IMemberDAO接口实现member数据表的配置
package com.yootk.dao;import com.yootk.vo.Member;
import org.apache.ibatis.annotations.Mapper;import java.util.List;@Mapper
public interface IMemberDAO { // 定义DAO接口public List<Member> findAll(); // 查询全部
}
5、 【microboot-database子模块】分页配置
package com.yootk.config;import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;@Configuration
public class MybatisPlusConfig { // Mybatis拦截器配置@Beanpublic MybatisPlusInterceptor getMybatisPlusInterceptor() {MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL) // 使用MySQL分页实现);return interceptor;}
}
6、 【microboot-database子模块】修改IMemberDAO数据接口,要存在有继承的父接口
package com.yootk.dao;import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.yootk.vo.Member;
import org.apache.ibatis.annotations.Mapper;import java.util.List;@Mapper
public interface IMemberDAO extends BaseMapper<Member> { // 定义DAO接口public List<Member> findAll(); // 查询全部,这个方法一定要存在有映射实现
}
7、【microboot-database子模块】修改IMemberService 业务接口,在该接口之中实现核心的CRUD数据处理操作
package com.yootk.service;import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yootk.vo.Member;import java.util.List;
import java.util.Set;public interface IMemberService {public List<Member> list();public Member get(String mid); // 根据ID查询public boolean add(Member vo); // 增加数据public boolean delete(Set<String> ids); // 数据删除public Map<String, Object> listSplit(String column, String keyword,Integer currentPage, Integer lineSize); // 分页查询
}
8、【microboot-database子模块】MemberServiceImpl
package com.yootk.service.impl.impl;import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yootk.dao.IMemberDAO;
import com.yootk.service.IMemberService;
import com.yootk.vo.Member;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.util.List;
import java.util.Set;@Service
public class MemberServiceImpl implements IMemberService {@Autowiredprivate IMemberDAO memberDAO;@Overridepublic List<Member> list() {return this.memberDAO.findAll();}@Overridepublic Member get(String mid) {return this.memberDAO.selectById(mid);}@Overridepublic boolean add(Member vo) {return this.memberDAO.insert(vo) > 0;}@Overridepublic boolean delete(Set<String> ids) {return this.memberDAO.deleteBatchIds(ids) == ids.size();}@Overridepublic Map<String, Object> listSplit(String column, String keyword, Integer currentPage, Integer lineSize) {QueryWrapper<Member> wrapper = new QueryWrapper<>();wrapper.like(column, keyword); // 设置模糊查询操作int count = this.memberDAO.selectCount(wrapper); // 统计个数// 实现数据的查询处理IPage<Dept> page = this.memberDAO.selectPage(new Page<>(currentPage, lineSize, count), wrapper);Map<String, Object> map = new HashMap<>(); // 包装返回结果map.put("allMembers", page.getRecords()); //数据记录map.put("allRecorders", page.getTotal()); //总数map.put("allPages", page.getPages()); //页数return map;}
}
9、【microboot-database子模块】编写一个测试类,对当前的业务接口的功能进行测试
package com.yootk.test;import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yootk.StartSpringBootDatabaseApplication;
import com.yootk.service.IMemberService;
import com.yootk.vo.Member;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.context.web.WebAppConfiguration;import java.util.Date;
import java.util.Set;@ExtendWith(SpringExtension.class) // 使用JUnit5测试工具
@WebAppConfiguration // 启动WEB运行环境
@SpringBootTest(classes = StartSpringBootDatabaseApplication.class) // 配置程序启动类
public class TestMemberService { // 编写测试类@Autowiredprivate IMemberService memberService;@Testpublic void testFindAll() {System.out.println(this.memberService.list());}@Testpublic void testGet() {System.out.println(this.memberService.get("yootk"));}@Testpublic void testAdd() {Member vo = new Member();vo.setMid("yootk - " + Math.random());vo.setName("沐言科技");vo.setBirthday(new Date());vo.setSalary(865.0);vo.setContent("www.yootk.com");vo.setAge(16);System.out.println(this.memberService.add(vo));}@Testpublic void testSplit() {Map<String, Object> map = this.memberService.listSplit("name", "沐言", 1, 5);System.out.println("总页数:" + map.get(allPages));System.out.println("总记录数:" + map.get(allRecorders));System.out.println("响应内容:" + map.get(allMembers));}@Testpublic void testDelete() {Set<String> ids = Set.of("muyan", "yootk", "lixinghua");this.memberService.delete(ids);}
}
10、【microboot-database子模块】
package com.yootk.action;import com.yootk.common.action.abs.AbstractBaseAction;
import com.yootk.service.IMemberService;
import com.yootk.vo.Member;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;@RestController
@RequestMapping("/member/*")
@Slf4j
public class MemberAction extends AbstractBaseAction {@Autowiredprivate IMemberService memberService;@RequestMapping("list")public Object list() {log.info("查询全部Member数据。");return this.memberService.list();}@RequestMapping("get")public Object get(String mid) {log.info("查询用户数据:{}", mid);return this.memberService.get(mid);}@RequestMapping("add")public Object add(Member member) {log.info("增加新的用户数据:{}", member);return this.memberService.add(member);}@RequestMapping("delete")public Object delete(String ... id) {log.info("根据ID删除数据:{}", id);Set<String> ids = new HashSet<>();ids.addAll(Arrays.asList(id));return this.memberService.delete(ids);}@RequestMapping("split")public Map<String, Object> split(String column, String keyword, int currentPage, int lineSize) {log.info("数据分页显示,查询模糊列:{}、查询关键字:{}、当前页:{}、每页行数:{}");return this.memberService.listSplit(column, keyword, currentPage, lineSize);}
}
基于Bean方式
现在为止实现的Mybatis 整个的流程都是基于starter组件“mybatis-plus-boot-starter”实现的,所以所有的配置项只需要在 application.yml里面进行定义即可,但是除了这种操作之外,也可以直接基于Bean的模式手工配置。
1、【microboot项目】修改配置文件,引入所需要的相关依赖库:
dependences.gradle
ext.versions = [ // 定义所有要使用的版本号springboot : '2.4.3', // SpringBoot版本号junit : '5.7.1', // 配置JUnit测试工具的版本编号junitPlatformLauncher : '1.7.1', // JUnit测试工具运行平台版本编号lombok : '1.18.18', // Lombok插件对应的版本号mysql : '8.0.25', // MySQL驱动的版本druid : '1.2.6', // Druid版本mybatisplus : '3.4.3', // Mybatis-plus-SpringBoot整合依赖
]
ext.libraries = [ // 定义所有的依赖库'spring-boot-gradle-plugin': "org.springframework.boot:spring-boot-gradle-plugin:${versions.springboot}",// 以下的配置为与项目用例测试有关的依赖'junit-jupiter-api': "org.junit.jupiter:junit-jupiter-api:${versions.junit}",'junit-vintage-engine': "org.junit.vintage:junit-vintage-engine:${versions.junit}",'junit-jupiter-engine': "org.junit.jupiter:junit-jupiter-engine:${versions.junit}",'junit-platform-launcher': "org.junit.platform:junit-platform-launcher:${versions.junitPlatformLauncher}",'junit-bom': "org.junit:junit-bom:${versions.junit}",// 以下的配置为Lombok组件有关的依赖'lombok': "org.projectlombok:lombok:${versions.lombok}",// 以下的配置为数据库开发所需要的依赖:'mysql-connector-java': "mysql:mysql-connector-java:${versions.mysql}",'druid-spring-boot-starter': "com.alibaba:druid-spring-boot-starter:${versions.druid}",'spring-jdbc': "org.springframework:spring-jdbc:${versions.springJdbc}",'druid': "com.alibaba:druid:${versions.druid}",// 以下的配置为MyBatis开发框架所需要的依赖:'mybatis-plus': "com.baomidou:mybatis-plus:${versions.mybatisPlus}",//'mybatis-plus-boot-starter': "com.baomidou:mybatis-plus-boot-starter:${versions.mybatisPlus}",
]
project('microboot-database') { // 子模块dependencies { // 配置子模块依赖compile(project(':microboot-common')) // 引入其他子模块compile(libraries.'druid') // 添加原始依赖compile(libraries.'mysql-connector-java')// compile(libraries.'druid-spring-boot-starter') // 删除掉此依赖库配置compile(libraries.'mybatis-plus')}
}
2、【microboot项目】如果要想进行Bean的配置,则一些相关的配置内容也应该定义在资源文件里面,那么本次就直接继续使用之前自动配置时所提供的配置项:
mybatis-plus:config-location: classpath:META-INF/mybatis/mybatis.cfg.xml # mybatis配置文件所在路径type-aliases-package: com.yootk.vo # 定义所有操作类的别名所在包mapper-locations: classpath:META-INF/mybatis/mapper/**/*.xml # 所有的mapper映射文件global-config: # 全局配置db-config:logic-not-delete-value: 0 # 数据删除前logic-delete-value: 1 # 数据删除后
3、【microboot-database子模块】创建MyBatisPlusConfig 配置类,引入SqlSessionFactoryBean 实例,并且进行MyBatisPlus相关环境定义
package com.yootk.config;import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.mybatis.spring.boot.autoconfigure.SpringBootVFS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;import javax.sql.DataSource;@Configuration
public class MybatisPlusConfig { // Mybatis拦截器配置private ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();@Beanpublic MybatisPlusInterceptor getMybatisPlusInterceptor() {MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL) // 使用MySQL分页实现);return interceptor;}@Bean("mybatisSqlSessionFactoryBean")public MybatisSqlSessionFactoryBean getMybatisSqlSessionFactoryBean(@Autowired DataSource dataSource, // 要使用的数据源@Value("${mybatis-plus.config-location}") Resource configLocation, // 资源文件路径@Value("${mybatis-plus.type-aliases-package}") String typeAliasesPackage, // 扫描别名@Value("${mybatis-plus.mapper-locations}") String mapperLocations, // Mapping映射路径@Value("${mybatis-plus.global-config.db-config.logic-not-delete-value}") String logicNotDeleteValue,@Value("${mybatis-plus.global-config.db-config.logic-delete-value:}") String logicDeleteValue) throws Exception {MybatisSqlSessionFactoryBean mybatisPlus = new MybatisSqlSessionFactoryBean();mybatisPlus.setDataSource(dataSource); // 配置项目中要使用的数据源mybatisPlus.setVfs(SpringBootVFS.class); // 配置程序的扫描类mybatisPlus.setTypeAliasesPackage(typeAliasesPackage); // 扫描包的别名Resource[] mappings = this.resourcePatternResolver.getResources(mapperLocations);mybatisPlus.setMapperLocations(mappings);GlobalConfig.DbConfig dbConfig = new GlobalConfig.DbConfig(); // 数据配置dbConfig.setLogicNotDeleteValue(logicNotDeleteValue); // 未删除时的数据内容dbConfig.setLogicDeleteValue(logicDeleteValue); // 删除时的数据内容GlobalConfig globalConfig = new GlobalConfig(); // 定义全局配置globalConfig.setDbConfig(dbConfig); // 全局配置项mybatisPlus.setGlobalConfig(globalConfig);return mybatisPlus;}
}
此时已经成功的使用了自定义的MybatisPlus配置Bean代替了starter配置 (starter内部也只是封装了这样的一种配置类而已,本质上都是相同的)。