1.创建spring项目带spring web
2.引入依赖,并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>
3.在resource中的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
4.在src/main/java/com.example.list包下新建GenCode并添加以下代码,执行run GenCode
package com.example.list; 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.list"; String tableName = "scheduleList" ; // 代码生成器 AutoGenerator mpg = new AutoGenerator(); // 全局配置 GlobalConfig gc = new GlobalConfig(); String projectPath = System.getProperty("user.dir"); gc.setOutputDir(projectPath + "/src/main/java"); gc.setAuthor("小白"); 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(); } }
5.Application中添加 @MapperScan 注解,修改包名为刚生成的mapper目录@MapperScan("com.example.list.DataMapper.mapper")
6.编写测试类test/java/xxxTest中添加,获取表里的一个数据。(修改包名)接着run testSelect 可查看到表信息
@SpringBootTest class NiceApplicationTests { @Autowired(required = false) private SchedulelistMapper SchedulelistMapper; @Test public void testSelect() { System.out.println(("----- selectAll method test ------")); List<Schedulelist> userList = SchedulelistMapper.selectList(null); // Assert.assertEquals(5, userList.size()); userList.forEach(System.out::println); } }
7.执行 SQL 分析打印,并load maven changes
P6spy 依赖引入
<dependency>
<groupId>p6spy</groupId>
<artifactId>p6spy</artifactId>
<version>3.9.1</version>
</dependency>
8.修改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 spring.datasource.driver-class-name: com.p6spy.engine.spy.P6SpyDriver spring.datasource.url: jdbc:p6spy:mysql://192.168.0.248:3306/hyj_test
9.在resource中添加 file文件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
10.编写controller
@Resource private ISchedulelistService scheduleTaskService; private static final String template = "Hello, %s!"; // private final AtomicLong counter = new AtomicLong(); @GetMapping("/yo") public List<Schedulelist> yo(@RequestParam(value = "name", defaultValue = "World") String name) { return scheduleTaskService.getSchedulelistList(); } }
11.在ISchedulelistService中添加
List<Schedulelist> getSchedulelistList();
12.在SchedulelistServiceImpl中添加
@Resource private SchedulelistMapper schedulelistMapper; public List<Schedulelist> getSchedulelistList(){ return schedulelistMapper.selectList(null); }
13.run ListApplication
14. http://localhost:8080/datamapper/schedulelist/yohttp://localhost:8080/datamapper/schedule/list 可返回表信息
15.在controller中添加 接口 /scheduleAdd 接受参数 添加一条数据到表中 返回添加结果
@GetMapping("/add") public List<Schedulelist> yo2(@RequestParam(value = "name", defaultValue = "World") String name) { scheduleTaskService.getSchedulelistAdd(); return scheduleTaskService.getSchedulelistList(); }
在service中添加方法
void getSchedulelistAdd();
在impl中添加
public void getSchedulelistAdd(){ Schedulelist schedulelist=new Schedulelist(); schedulelist.setWay("77885544111"); schedulelistMapper.insert(schedulelist); }
run application,登 http://localhost:8080/datamapper/schedule/add得
16.在controller中添加 接口 /scheduleDel 接受参数id 删除该数据 返回删除结果
@GetMapping("/del") public List<Schedulelist> yo3(@RequestParam(value = "name", defaultValue = "World") String name) { scheduleTaskService.getSchedulelistDel(); return scheduleTaskService.getSchedulelistList();
在service中添加方法
void getSchedulelistDel();
在impl中添加
public void getSchedulelistDel(){ schedulelistMapper.deleteById(9); }
run application,登http://localhost:8080/datamapper/schedule/del得