ICode9

精准搜索请尝试: 精确搜索
首页 > 数据库> 文章详细

Spring+SQL

2021-09-11 18:06:06  阅读:184  来源: 互联网

标签:00 01 mybatisplus Spring baomidou SQL new com


新建表

DROP TABLE IF EXISTS schedule_task;


CREATE TABLE schedule_task
(
    taskid  int    auto_increment   COMMENT '任务ID1',
    taskname VARCHAR(30) NULL DEFAULT NULL COMMENT '任务名称',
    Label VARCHAR(30) NULL DEFAULT NULL COMMENT '标签',
    way VARCHAR(30) NULL DEFAULT NULL COMMENT '执行方式',
    tasktime TIMESTAMP(6) NULL DEFAULT NULL COMMENT '任务节点',
    state VARCHAR(30) NULL DEFAULT NULL COMMENT '状态',
    PRIMARY KEY (taskid)
);
INSERT INTO schedule_task  VALUES
(1, 'Jone', '1', '1','1970-01-01 00:00:01', 'haha'),
(2, 'Jack', '2','1', '1970-01-01 00:00:01', 'kaka'),
(3, 'Tom', '3', '1','1970-01-01 00:00:01', 'fafa'),
(4, 'Sandy', '4', '1','1970-01-01 00:00:01', 'gaga'),
(5, 'Billie', '5','1', '1970-01-01 00:00:01', 'xaxa'),
(6, 'hedy', '4', '1','1970-01-01 00:00:01', 'gaga'),
(7, 'Sam', '4', '1','1970-01-01 00:00:01', 'gaga');

 idea中新建spring項目

 

 添加依赖(还需要 mysql,lomck,freemake,generator)并执行 load maven changes. 

<dependency>
   <groupId>com.baomidou</groupId>
   <artifactId>mybatis-plus-boot-starter</artifactId>
   <version>3.4.3.1</version>
</dependency>
<dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <scope>runtime</scope>
</dependency>
<dependency>
   <groupId>com.baomidou</groupId>
   <artifactId>mybatis-plus-generator</artifactId>
   <version>3.4.1</version>
</dependency>
<dependency>
   <groupId>org.freemarker</groupId>
   <artifactId>freemarker</artifactId>
   <version>2.3.31</version>
</dependency>
<dependency>
   <groupId>org.projectlombok</groupId>
   <artifactId>lombok</artifactId>
   <version>1.18.20</version>
   <scope>provided</scope>
</dependency>

 

在application.properties贴上

spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://192.168.0.248:3306/hyj_test
spring.datasource.username=hyj
spring.datasource.password=123456
spring.datasource.driver-class-name =com.mysql.jdbc.Driver

 

使用GenCode创建表的control,mapper. 复制generator类,并修改表名和包名,生成mapper.

更改后代码如下,右键run GenCode main()生成mapper。

package com.example.nice;



import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

// 演示例子,执行 main 方法控制台输入模块表名回车自动生成对应项目目录中
public class GenCode {

//这个会帮你创建mapper.但需要设置 表名 包名
//    表名是: excel
//    包名是: com.test.plusdemo



    public static void main(String[] args) {
        String  packageName = "com.example.nice";
        String  tableName = "schedule_task" ;
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        gc.setOutputDir(projectPath + "/src/main/java");
        gc.setAuthor("sakura");
        gc.setOpen(false);
        // gc.setSwagger2(true); 实体属性 Swagger2 注解
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://192.168.0.248:3306/hyj_test?useUnicode=true&useSSL=false&characterEncoding=utf8");
        // dsc.setSchemaName("public");
        dsc.setDriverName("com.mysql.jdbc.Driver");
        dsc.setUsername("hyj");
        dsc.setPassword("123456");
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName("DataMapper");
        pc.setParent(packageName);
        mpg.setPackageInfo(pc);

        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };

        // 如果模板引擎是 freemarker
        String templatePath = "/templates/mapper.xml.ftl";
        // 如果模板引擎是 velocity
        // String templatePath = "/templates/mapper.xml.vm";

        // 自定义输出配置
        List<FileOutConfig> focList = new ArrayList<>();
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
                return projectPath + "/src/main/resources/mapper/" + pc.getModuleName()
                        + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });
        /*
        cfg.setFileCreate(new IFileCreate() {
            @Override
            public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
                // 判断自定义文件夹是否需要创建
                checkDir("调用默认方法创建的目录,自定义目录用");
                if (fileType == FileType.MAPPER) {
                    // 已经生成 mapper 文件判断存在,不想重新生成返回 false
                    return !new File(filePath).exists();
                }
                // 允许生成模板文件
                return true;
            }
        });
        */
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();

        // 配置自定义输出模板
        //指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
        // templateConfig.setEntity("templates/entity2.java");
        // templateConfig.setService();
        // templateConfig.setController();

        templateConfig.setXml(null);
        mpg.setTemplate(templateConfig);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setSuperEntityClass("");
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        // 公共父类
        strategy.setSuperControllerClass("");
        // 写于父类中的公共字段
//        strategy.setSuperEntityColumns("id");
        strategy.setInclude(tableName.split(","));
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix(pc.getModuleName() + "_");
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }

}

 

在 Spring Boot 启动类中添加 @MapperScan 注解,修改包名为刚生成的mapper目录

修改后的注释如下:

@MapperScan("com.example.nice.DataMapper.mapper")

 

编写测试类,获取表里的一个数据。(修改包名)

@SpringBootTest
class NiceApplicationTests {

    @Autowired(required = false)
    private ScheduleTaskMapper ScheduleTaskMapper;

    @Test
    public void testSelect() {
        System.out.println(("----- selectAll method test ------"));
        List<ScheduleTask> userList = ScheduleTaskMapper.selectList(null);
//    Assert.assertEquals(5, userList.size());
        userList.forEach(System.out::println);
    }

}

 

run testSelect (右键点方法名)得到 

 

执行 SQL 分析打印

P6spy 依赖引入

<dependency>
   <groupId>p6spy</groupId>
   <artifactId>p6spy</artifactId>
   <version>3.9.1</version>
</dependency>

application.yml 配置:

修改后如下:

spring.datasource.driver-class-name: com.p6spy.engine.spy.P6SpyDriver
spring.datasource.url: jdbc:p6spy:mysql://192.168.0.248:3306/hyj_test

 

spy.properties 配置:

新建spy.properties

贴上:

#3.2.1以上使用
modulelist=com.baomidou.mybatisplus.extension.p6spy.MybatisPlusLogFactory,com.p6spy.engine.outage.P6OutageFactory
#3.2.1以下使用或者不配置
#modulelist=com.p6spy.engine.logging.P6LogFactory,com.p6spy.engine.outage.P6OutageFactory
# 自定义日志打印
logMessageFormat=com.baomidou.mybatisplus.extension.p6spy.P6SpyLogger
#日志输出到控制台
appender=com.baomidou.mybatisplus.extension.p6spy.StdoutLogger
# 使用日志系统记录 sql
#appender=com.p6spy.engine.spy.appender.Slf4JLogger
# 设置 p6spy driver 代理
deregisterdrivers=true
# 取消JDBC URL前缀
useprefix=true
# 配置记录 Log 例外,可去掉的结果集有error,info,batch,debug,statement,commit,rollback,result,resultset.
excludecategories=info,debug,result,commit,resultset
# 日期格式
dateformat=yyyy-MM-dd HH:mm:ss
# 实际驱动可多个
#driverlist=org.h2.Driver
# 是否开启慢SQL记录
outagedetection=true
# 慢SQL记录标准 2 秒
outagedetectioninterval=2

 

编写controller

 run application

 

 

 

 

标签:00,01,mybatisplus,Spring,baomidou,SQL,new,com
来源: https://blog.csdn.net/m0_59348479/article/details/120233396

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有