目录
学习笔记
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 { @Autowired private UserDao userDao; @Test void testSelectAll() { List<User> userList = userDao.selectList(null); System.out.println(userList); } //插入 @Test void 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 ? "插入成功" : "插入失败"); } //删除 @Test public void testRemove() { System.out.println(userDao.deleteById(4) > 0 ? "OK!" : "FAIL!"); } //更新 @Test public void testUpdate() { User user = new User(); user.setName("齐天大圣"); user.setId(4L); System.out.println(userDao.updateById(user)); } //查询 @Test public void testFind() { System.out.println(userDao.selectById(4)); } //分页 @Test public void userPage() { Page<User> page = new Page<>(1, 4); IPage<User> userIPage = userDao.selectPage(page, null); System.out.println("总共数据有:" + userIPage.getTotal()); System.out.println("总共的页数为:" + userIPage.getPages()); System.out.println("拿到的数据为:" + userIPage.getRecords()); } //使用DQL //条件查询,查询所有年龄小于30岁的人 @Test public void testUserQueryWrapper() { QueryWrapper<User> qw = new QueryWrapper<>(); qw = qw.lt("age", 30); //lt : less then List<User> userList = userDao.selectList(qw); userList.forEach(System.out::println); } //在DQL中使用lambda //条件查询,查询所有年龄小于30岁的人 @Test public void testUserQueryWrapperUseLambda() { LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<>(); qw = qw.lt(User::getAge, 30); List<User> userList = userDao.selectList(qw); userList.forEach(System.out::println); } //条件查询,查询所有年龄大于10小于30岁的人 @Test public void testUserQueryWrapper2UseLambda() { LambdaQueryWrapper<User> 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<User> userList = userDao.selectList(qw); userList.forEach(System.out::println); } //空值校验 @Test public void testUserQueryWrapper3UseLambda() { //模拟空数据 User2 user2 = new User2(); user2.setAge(2); //构建查询 LambdaQueryWrapper<User> qw = new LambdaQueryWrapper<>(); //校验是否为空 qw = qw.lt(null != user2.getAge2(), User::getAge, 30); qw = qw.lt(null != user2.getAge(), User::getAge, 30); List<User> userList = userDao.selectList(qw); userList.forEach(System.out::println); } //查询指定字段 @Test public void testUserQueryWrapper4UseLambda() { LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<User>(); lqw.select(User::getId, User::getName, User::getAge); List<User> userList = userDao.selectList(lqw); System.out.println(userList); } //聚合查询 @Test public void testUserQueryWrapper5UseLambda() { QueryWrapper<User> lqw = new QueryWrapper<User>(); //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 user lqw.select("avg(age) as avgAge"); //SELECT avg(age) as avgAge FROM user List<Map<String, Object>> userList = userDao.selectMaps(lqw); System.out.println(userList); } //等值查询 @Test public void testUserQueryWrapper6UseLambda() { LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<User>(); //验证用户的密码是否正确 lqw.eq(User::getName, "Jerry").eq(User::getPassword, "jerry"); User loginUser = userDao.selectOne(lqw); System.out.println(loginUser); } //范围查询 @Test public void testUserQueryWrapper7UseLambda() { LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<User>(); lqw.between(User::getAge, 10, 30); //SELECT id,name,password,age,tel FROM user WHERE (age BETWEEN ? AND?) List<User> userList = userDao.selectList(lqw); System.out.println(userList); } //模糊查询 //like():前后加百分号,如 %J% //likeLeft():前面加百分号,如 %J //likeRight():后面加百分号,如 J% @Test public void testUserQueryWrapper8UseLambda() { LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<User>(); lqw.likeRight(User::getName, "J"); //SELECT id,name,password,age,tel FROM user WHERE (name LIKE J%) List<User> userList = userDao.selectList(lqw); System.out.println(userList); } //排序 @Test public void testUserQueryWrapper9UseLambda() { LambdaQueryWrapper<User> lwq = new LambdaQueryWrapper<User>(); /* * condition :条件,返回boolean, 当condition为true,进行排序,如果为false,则不排序 * isAsc:是否为升序,true为升序,false为降序 * columns:需要操作的列 * orderBy排序 condition:条件,true则添加排序,false则不添加排序 isAsc:是否为升序,true升序,false降序 columns:排序字段,可以有多个 orderByAsc/Desc(单个column):按照指定字段进行升序/降序 orderByAsc/Desc(多个column):按照多个字段进行升序/降序 orderByAsc/Desc condition:条件,true添加排序,false不添加排序 多个columns:按照多个字段进行排序 */ lwq.orderBy(true,false, User::getId); List<User> users = userDao.selectList(lwq); users.forEach(System.out::println); } }
其他知识点
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:用户手工输入id ASSIGN_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_id 10-> MP会默认将模型类的类名名首字母小写作为表名使用,假如所有的表名称都以tbl_开头 ,我们怎么一次设置使得所有实体类都默认应该tbl_xxx? 配置文件 mybatis-plus: global-config: db-config: table-prefix: tbl_ 设置表的前缀内容,这样MP就会拿 tbl_加上模型类的首字母小写,就刚好组装成数据库的表名。 11-> 批量操作 批量删除 @Test void testDelete(){ //删除指定多条数据 List<Long> list = new ArrayList<>(); list.add(1402551342481838081L); list.add(1402553134049501186L); list.add(1402553619611430913L); userDao.deleteBatchIds(list); } ---------- 批量查询 @Test void testGetByIds(){ //查询指定多条数据 List<Long> 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<User> { //查询所有数据包含已经被删除的数据 @Select("select * from tbl_user") public List<User> selectAll(); } 14-> 怎么全局配置软删除? 配置文件 mybatis-plus: global-config: db-config: # 逻辑删除字段名 logic-delete-field: deleted # 逻辑删除字面值:未删除为0 logic-not-delete-value: 0 # 逻辑删除字面值:删除为1 logic-delete-value: 1 15-> 乐观锁的使用 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-> 快速开发 代码生成器
yaml配置文件
application.yaml spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://127.0.0.1:3306/mybatisplus_db?useSSL=false&serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8 username: root password: xxxxx type: com.alibaba.druid.pool.DruidDataSource main: banner-mode: off # mybatis-plus日志控制台输出 mybatis-plus: configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl global-config: banner: off # 关闭mybatisplus启动图
代码生成器
新建项目
删除无关内容
补全maven依赖
建议直接替换
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.example</groupId> <artifactId>SpringBoot_UserCodeAuto</artifactId> <version>0.0.1-SNAPSHOT</version> <name>SpringBoot_UserCodeAuto</name> <description>SpringBoot_UserCodeAuto</description> <properties> <java.version>1.8</java.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <spring-boot.version>2.3.7.RELEASE</spring-boot.version> </properties> <!-- springmvc--> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- 数据库--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.2</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.16</version> </dependency> <!--velocity模板引擎--> <dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity-engine-core</artifactId> <version>2.3</version> </dependency> <!--代码生成器--> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> <version>3.4.1</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-dependencies</artifactId> <version>${spring-boot.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.1</version> <configuration> <source>1.8</source> <target>1.8</target> <encoding>UTF-8</encoding> </configuration> </plugin> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <version>2.3.7.RELEASE</version> <configuration> <mainClass>com.learn.codeauto.SpringBootUserCodeAutoApplication</mainClass> </configuration> <executions> <execution> <id>repackage</id> <goals> <goal>repackage</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </project>
新建类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); //设置是否启用lombok autoGenerator.setStrategy(strategyConfig); //2.执行生成操作 autoGenerator.execute(); } }
右击直接运行当前文件
生成结果