目录
学习笔记
SQL文件
练习类
其他知识点
yaml配置文件
代码生成器
SQL文件
SQL
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`password` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`age` int(3) NULL DEFAULT NULL,
`tel` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`isdelete` int(1) NULL DEFAULT NULL,
`version` int(255) NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 5 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES (1, 'Tom', 'tom', 3, '18866668888', 0, NULL);
INSERT INTO `user` VALUES (2, 'Jerry', 'jerry', 4, '16688886666', 0, NULL);
INSERT INTO `user` VALUES (3, 'Jock', '123456', 41, '18812345678', 0, NULL);
SET FOREIGN_KEY_CHECKS = 1;
package com.learn.plue;import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; 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.learn.plue.Dao.UserDao; import com.learn.plue.entity.User; import com.learn.plue.entity.User2; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest;import java.util.List; import java.util.Map;@SpringBootTest class SpringbootMybatisplusApplicationTests {@Autowiredprivate UserDao userDao;@Testvoid testSelectAll() {ListuserList = userDao.selectList(null);System.out.println(userList);}//插入@Testvoid testSave() {User user = new User();user.setName("黑马程序员");user.setPassword("itheima");user.setAge(12);user.setTel("111");int row = userDao.insert(user);System.out.println(row > 0 ? "插入成功" : "插入失败");}//删除@Testpublic void testRemove() {System.out.println(userDao.deleteById(4) > 0 ? "OK!" : "FAIL!");}//更新@Testpublic void testUpdate() {User user = new User();user.setName("齐天大圣");user.setId(4L);System.out.println(userDao.updateById(user));}//查询@Testpublic void testFind() {System.out.println(userDao.selectById(4));}//分页@Testpublic void userPage() {Page page = new Page<>(1, 4);IPage userIPage = userDao.selectPage(page, null);System.out.println("总共数据有:" + userIPage.getTotal());System.out.println("总共的页数为:" + userIPage.getPages());System.out.println("拿到的数据为:" + userIPage.getRecords());}//使用DQL//条件查询,查询所有年龄小于30岁的人@Testpublic void testUserQueryWrapper() {QueryWrapper qw = new QueryWrapper<>();qw = qw.lt("age", 30);//lt : less thenList userList = userDao.selectList(qw);userList.forEach(System.out::println);}//在DQL中使用lambda//条件查询,查询所有年龄小于30岁的人@Testpublic void testUserQueryWrapperUseLambda() {LambdaQueryWrapper qw = new LambdaQueryWrapper<>();qw = qw.lt(User::getAge, 30);List userList = userDao.selectList(qw);userList.forEach(System.out::println);}//条件查询,查询所有年龄大于10小于30岁的人@Testpublic void testUserQueryWrapper2UseLambda() {LambdaQueryWrapper qw = new LambdaQueryWrapper<>();qw = qw.lt(User::getAge, 30).gt(User::getAge, 10);//如果要使用or的话需要加上//qw= qw.lt(User::getAge, 30).or().gt(User::getAge,10);List userList = userDao.selectList(qw);userList.forEach(System.out::println);}//空值校验@Testpublic void testUserQueryWrapper3UseLambda() {//模拟空数据User2 user2 = new User2();user2.setAge(2);//构建查询LambdaQueryWrapper qw = new LambdaQueryWrapper<>();//校验是否为空qw = qw.lt(null != user2.getAge2(), User::getAge, 30);qw = qw.lt(null != user2.getAge(), User::getAge, 30);List userList = userDao.selectList(qw);userList.forEach(System.out::println);}//查询指定字段@Testpublic void testUserQueryWrapper4UseLambda() {LambdaQueryWrapper lqw = new LambdaQueryWrapper ();lqw.select(User::getId, User::getName, User::getAge);List userList = userDao.selectList(lqw);System.out.println(userList);}//聚合查询@Testpublic void testUserQueryWrapper5UseLambda() {QueryWrapper lqw = new QueryWrapper ();//lqw.select("count(*) as count");//SELECT count(*) as count FROM user//lqw.select("max(age) as maxAge");//SELECT max(age) as maxAge FROM user//lqw.select("min(age) as minAge");//SELECT min(age) as minAge FROM user//lqw.select("sum(age) as sumAge");//SELECT sum(age) as sumAge FROM userlqw.select("avg(age) as avgAge");//SELECT avg(age) as avgAge FROM userList
1-> 当此字段在表中不存在时 @TableField(exist = false) private String my1;2-> 当表中的字段与当前字段不一致时 @TableField(value = "数据库中表的字段") private String cs;3-> 当需要限制某些数据不被查询时 @TableField(select = false) private String my2;4-> 当当前实体类的class名与表名不一致时 @TableName("数据库中的表名") public class User{ xx; xxx; }5-> 设置主键自增 @TableId(type = IdType.AUTO) private Long id; 当使用这个的时候必须保证数据库中开启了主键自增 其他可选类型 ---》NONE: 不设置id生成策略INPUT:用户手工输入idASSIGN_ID:雪花算法生成id(可兼容数值型与字符串型)ASSIGN_UUID:以UUID生成算法作为id生成策略 6-> 设置分布式ID ASSIGN_ID @TableId(type = IdType.ASSIGN_ID) private Long id; 注:生成的id为随机的Long类型的数据7-> 设置分布式ID ASSIGN_UUID @TableId(type = IdType.ASSIGN_UUID) private String id; 注:生产的id为随机的String类型的数据 数据库中主键的类型应该改成String类型8-> 生成比较 NONE: 不设置id生成策略,MP不自动生成,约等于INPUT,所以这两种方式都需要用户手动设 置,但是手动设置第一个问题是容易出现相同的ID造成主键冲突,为了保证主键不冲突就需要做很 多判定,实现起来比较复杂 AUTO:数据库ID自增,这种策略适合在数据库服务器只有1台的情况下使用,不可作为分布式ID使用 ASSIGN_UUID:可以在分布式的情况下使用,而且能够保证唯一,但是生成的主键是32位的字符 串,长度过长占用空间而且还不能排序,查询性能也慢 ASSIGN_ID:可以在分布式的情况下使用,生成的是Long类型的数字,可以排序性能也高,但是 生成的策略和服务器时间有关,如果修改了系统时间就有可能导致出现重复主键 综上所述,每一种主键策略都有自己的优缺点,根据自己项目业务的实际情况来选择使用才是最明 智的选择9-> 如何一次更改,使得所有的实体类的主键都递增那??? 配置文件 mybatis-plus:global-config:db-config:id-type: assign_id10-> MP会默认将模型类的类名名首字母小写作为表名使用,假如所有的表名称都以tbl_开头 ,我们怎么一次设置使得所有实体类都默认应该tbl_xxx? 配置文件 mybatis-plus:global-config:db-config:table-prefix: tbl_ 设置表的前缀内容,这样MP就会拿 tbl_加上模型类的首字母小写,就刚好组装成数据库的表名。11-> 批量操作 批量删除 @Test void testDelete(){ //删除指定多条数据 Listlist = new ArrayList<>(); list.add(1402551342481838081L); list.add(1402553134049501186L); list.add(1402553619611430913L); userDao.deleteBatchIds(list); } ---------- 批量查询 @Test void testGetByIds(){ //查询指定多条数据 List list = new ArrayList<>(); list.add(1L); list.add(3L); list.add(4L); userDao.selectBatchIds(list); } ----------- 12-> MP怎么实现软删除? @TableLogic(value="0",delval="1") //value为正常数据的值,delval为删除数据的值 private Integer deleted; @Test void testDelete(){ userDao.deleteById(1L); }13-> 软删除之后,这么拿到所有数据(包括软删除的)? 使用mybatis注解查询,才可以查到,MP的查询是查不到的!! @Mapper public interface UserDao extends BaseMapper { //查询所有数据包含已经被删除的数据 @Select("select * from tbl_user") public List selectAll(); }14-> 怎么全局配置软删除? 配置文件 mybatis-plus:global-config:db-config:# 逻辑删除字段名logic-delete-field: deleted# 逻辑删除字面值:未删除为0logic-not-delete-value: 0# 逻辑删除字面值:删除为1logic-delete-value: 115-> 乐观锁的使用 1 添加配置类 @Configuration public class MpConfig { @Bean public MybatisPlusInterceptor mpInterceptor() { //1.定义Mp拦截器 MybatisPlusInterceptor mpInterceptor = new MybatisPlusInterceptor(); //2.添加乐观锁拦截器 mpInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor()); return mpInterceptor; } }2 数据库中加字段,实体类中加字段 实体类:还要加注解 @Version private Integer version;3 使用 先查后更新 @Test void testUpdate(){ //1.先通过要修改的数据id将当前数据查询出来 User user = userDao.selectById(3L); //2.将要修改的属性逐一设置进去 user.setName("Jock888"); userDao.updateById(user); } 测试案例 @Test void testUpdate(){ //1.先通过要修改的数据id将当前数据查询出来 User user = userDao.selectById(3L); //version=3 User user2 = userDao.selectById(3L); //version=3 user2.setName("Jock aaa"); userDao.updateById(user2); //version=>4 user.setName("Jock bbb"); userDao.updateById(user); //verion=3?条件还成立吗? }16-> 快速开发 代码生成器
application.yaml spring:datasource:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://127.0.0.1:3306/mybatisplus_db?useSSL=false&serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8username: rootpassword: xxxxxtype: com.alibaba.druid.pool.DruidDataSourcemain:banner-mode: off# mybatis-plus日志控制台输出 mybatis-plus:configuration:log-impl: org.apache.ibatis.logging.stdout.StdOutImplglobal-config:banner: off # 关闭mybatisplus启动图
新建项目
删除无关内容
补全maven依赖
建议直接替换
4.0.0 com.example SpringBoot_UserCodeAuto 0.0.1-SNAPSHOT SpringBoot_UserCodeAuto SpringBoot_UserCodeAuto 1.8 UTF-8 UTF-8 2.3.7.RELEASE org.springframework.boot spring-boot-starter-web mysql mysql-connector-java runtime com.baomidou mybatis-plus-boot-starter 3.4.2 com.alibaba druid 1.1.16 org.apache.velocity velocity-engine-core 2.3 com.baomidou mybatis-plus-generator 3.4.1 org.springframework.boot spring-boot-devtools runtime true org.springframework.boot spring-boot-configuration-processor true org.projectlombok lombok true org.springframework.boot spring-boot-starter-test test org.junit.vintage junit-vintage-engine org.springframework.boot spring-boot-dependencies ${spring-boot.version} pom import org.apache.maven.plugins maven-compiler-plugin 3.8.1 1.8 1.8 UTF-8 org.springframework.boot spring-boot-maven-plugin 2.3.7.RELEASE com.learn.codeauto.SpringBootUserCodeAutoApplication repackage repackage 新建类CodeGenerator
复制以下代码并更改,相应配置
package com.learn.codeauto; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.generator.AutoGenerator; import com.baomidou.mybatisplus.generator.config.DataSourceConfig; import com.baomidou.mybatisplus.generator.config.GlobalConfig; import com.baomidou.mybatisplus.generator.config.PackageConfig; import com.baomidou.mybatisplus.generator.config.StrategyConfig;public class CodeGenerator {public static void main(String[] args) {//1.获取代码生成器的对象AutoGenerator autoGenerator = new AutoGenerator();//设置数据库相关配置DataSourceConfig dataSource = new DataSourceConfig();dataSource.setDriverName("com.mysql.cj.jdbc.Driver");dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/mybatisplus_db?useSSL=false&serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8");dataSource.setUsername("root");dataSource.setPassword("scm13503905942");autoGenerator.setDataSource(dataSource);//设置全局配置GlobalConfig globalConfig = new GlobalConfig();//设置代码生成位置,默认从当前项目的根目录globalConfig.setOutputDir(System.getProperty("user.dir") + "/src/main/java");globalConfig.setOpen(false); //设置生成完毕后是否打开生成代码所在的目录globalConfig.setAuthor("小梦"); //设置作者globalConfig.setFileOverride(true); //设置是否覆盖原始生成的文件globalConfig.setMapperName("%sDao"); //设置数据层接口名,%s为占位符,指//代模块名称globalConfig.setIdType(IdType.ASSIGN_ID); //设置Id生成策略autoGenerator.setGlobalConfig(globalConfig);//设置包名相关配置PackageConfig packageInfo = new PackageConfig();packageInfo.setParent("com.mycode"); //设置生成的包名,与代码所在位置不冲突,//二者叠加组成完整路径packageInfo.setEntity("domain"); //设置实体类包名packageInfo.setMapper("dao"); //设置数据层包名autoGenerator.setPackageInfo(packageInfo);//策略设置StrategyConfig strategyConfig = new StrategyConfig();// strategyConfig.setInclude("tbl_user"); //设置当前参与生成的表名,参数为可变参数// strategyConfig.setTablePrefix("tbl_"); //设置数据库表的前缀名称,模块名 =数据库表名 - 前缀名 例如: User = tbl_user - tbl_strategyConfig.setRestControllerStyle(true); //设置是否启用Rest风格strategyConfig.setVersionFieldName("version"); //设置乐观锁字段名strategyConfig.setLogicDeleteFieldName("deleted"); //设置逻辑删除字段名strategyConfig.setEntityLombokModel(true); //设置是否启用lombokautoGenerator.setStrategy(strategyConfig);//2.执行生成操作autoGenerator.execute();} }
右击直接运行当前文件
生成结果