Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

SpringBoot integrates Mybatis-plus and automatically generates related files. How to write the sample code?

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces how to write the sample code that SpringBoot integrates Mybatis-plus and automatically generates related files, the content is very detailed, interested friends can refer to, hope to be helpful to you.

Mybatis-Plus is an excellent Mybatis enhancement tool, which is currently updated to 3.1.1. Mybatis-Plus natively provides many methods of single table operation, which greatly simplifies the tedious operation of curd, while supporting the writing of xml configuration and custom sql. This article introduces SpringBoot2 integration Mybatis-Plus 3.1.0 and mybatis provides MysqlGenerator.java. You can generate corresponding bean, mapper.xml, mapper.java, service.java, serviceImpl.java, or even controller from specified database tables.

1.pom.xml adds related dependencies. Please note the version number:

4.0.0 org.springframework.boot spring-boot-starter-parent 2.6.1 com.asiainfo rocketmq-producer 0.0.1-SNAPSHOT rocketmq-producer Demo project for Spring Boot 1.8 org.springframework.boot spring-boot-starter org .springframework.boot spring-boot-starter-web mysql mysql-connector-java runtime org.springframework.boot spring-boot-starter-freemarker com.baomidou mybatis-plus-boot-starter 2.3 Com.alibaba druid 1.1.5 org.projectlombok lombok true org.springframework.boot spring-boot-starter-test test org.junit.vintage Junit-vintage-engine org.testng testng RELEASE compile org.springframework.boot spring-boot-maven-plugin Org.apache.maven.plugins maven-resources-plugin 2.7 org.apache.maven.shared maven-filtering 1.3 Src/main/resources * * / * .properties * * / .xml * * / * .yml true

2.application.yml

Server: port: 9999spring: application: name: springboot-mybatisPlus # database partial notes datasource: type: com.alibaba.druid.pool.DruidDataSource url: jdbc:mysql://localhost:3306/rocketmq?useUnicode=true&characterEncoding=utf-8&useSSL=false&autoReconect=true&serverTimezone=GMT%2b8 username: root password: root driver-class-name: com.mysql.jdbc.Driver filters: stat maxActive: 50 initialSize: 0 maxWait: 60000 minIdle: 1 timeBetweenEvictionRunsMillis: 60000 minEvictableIdleTimeMillis: 300000 validationQuery : select 1 from dual testWhileIdle: true testOnBorrow: false testOnReturn: false poolPreparedStatements: true maxOpenPreparedStatements: 20 removeAbandoned: true removeAbandonedTimeout: 180mybatis-plus: global-config: # logical deletion configuration db-config: # before deletion logic-not-delete-value: 1 # after deletion logic-delete-value: 0 configuration: map-underscore-to-camel-case: true auto-mapping-behavior: full log -impl: org.apache.ibatis.logging.stdout.StdOutImpl mapper-locations: classpath:mybatisplus/mapper/*.xml

3.MyBatisPlusConfig.java

Package com.asiainfo.crm.rocketmq.config;import com.baomidou.mybatisplus.mapper.ISqlInjector;import com.baomidou.mybatisplus.mapper.LogicSqlInjector;import com.baomidou.mybatisplus.plugins.PaginationInterceptor;import com.baomidou.mybatisplus.plugins.PerformanceInterceptor;import lombok.extern.slf4j.Slf4j;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.Profile / * @ author zhangpb * @ date 2021-12-15 14:13 * @ Description: * / @ Configuration@Slf4jpublic class MyBatisPlusConfig {/ * @ description: configure the paging plug-in * * @ author: zhangpb * @ date: 2019-1-15 10:17 * @ param: [] @ return: com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor * / @ Bean public PaginationInterceptor paginationInterceptor () {log.debug ("registering paging plug-ins") Return new PaginationInterceptor () } / * * @ description: SQL execution efficiency plug-in * * @ author: zhangpb * @ date: 19-1-24 4:59 * @ param: [] * @ return: com.baomidou.mybatisplus.extension.plugins.PerformanceInterceptor * / @ Bean @ Profile ({"test"}) / / set the dev test environment to open public PerformanceInterceptor performanceInterceptor () {return new PerformanceInterceptor () } / * is used for logical deletion. Versions after 3.1.1 do not need to configure this bean, but the project here uses * * @ author zhangpb * * @ return com.baomidou.mybatisplus.core.injector.ISqlInjector * / @ Bean public ISqlInjector sqlInjector () {return new LogicSqlInjector ();}}

4.MysqlGenerator.java

Package com.asiainfo.crm.rocketmq.config;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.TableFill;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 / * * @ author zhangpb * @ date 14:14 on 2021-12-15 * @ Description: * / public class MysqlGenerator {/ * generate * @ param args * / public static void main (String [] args) {/ / code generator AutoGenerator mpg = new AutoGenerator (); / / Global configuration GlobalConfig gc = new GlobalConfig () / / String projectPath = System.getProperty ("user.dir"); / / gc.setOutputDir (projectPath + "/ src/main/java"); String projectPath = "E://java-workspace//rocketmq//rocketmq_space//rocketmq//rocketmq-producer"; gc.setOutputDir (projectPath + "\\ src\\ main\\ java\ com\\ asiainfo\\ crm\\ rocketmq\ cell") / / TODO sets user name gc.setAuthor ("zhangpb"); gc.setOpen (true); / / service naming method gc.setServiceName ("% sService"); / / service impl naming method gc.setServiceImplName ("% sServiceImpl"); / / Custom file naming, note that% s automatically populates table entity attributes! Gc.setMapperName ("% sMapper"); gc.setXmlName ("% sMapper"); gc.setFileOverride (true); gc.setActiveRecord (true); / / XML second-tier cache gc.setEnableCache (false); / / XML ResultMap gc.setBaseResultMap (true); / / XML columList gc.setBaseColumnList (false); mpg.setGlobalConfig (gc) / / TODO data source configuration DataSourceConfig dsc = new DataSourceConfig (); dsc.setUrl ("jdbc:mysql://127.0.0.1:3306/rocketmq?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=UTC"); dsc.setDriverName ("com.mysql.jdbc.Driver"); dsc.setUsername ("root"); dsc.setPassword ("root"); mpg.setDataSource (dsc) / / TODO package configuration PackageConfig pc = new PackageConfig (); / / pc.setModuleName (scanner ("module name")); / / pc.setParent ("com.zhangpb.demodruid"); pc.setEntity ("entity"); pc.setService ("service"); pc.setServiceImpl ("service.impl"); mpg.setPackageInfo (pc) / / customize the fields to be populated: List tableFillList = new ArrayList () / / for example, each table has a creation time and modification time / / and this is basically universal. When added, when the creation time and modification time are modified at the same time, the modification time will be modified. / / although there are several automatic updates for databases like Mysql, databases like ORACLE do not, / / use the common field filling function. It can be realized and automatically updated by scene. / / configure / / TableFill createField = new TableFill ("gmt_create", FieldFill.INSERT); / / TableFill modifiedField = new TableFill ("gmt_modified", FieldFill.INSERT_UPDATE); / / tableFillList.add (createField); / / tableFillList.add (modifiedField) / / Custom configuration InjectionConfig cfg = new InjectionConfig () {@ Override public void initMap () {/ / to do nothing}}; List focList = new ArrayList () FocList.add (new FileOutConfig ("/ templates/mapper.xml.ftl") {@ Override public String outputFile (TableInfo tableInfo) {/ / Custom input file name return projectPath + "/ src/main/resources/mapper/" + "/" + tableInfo.getEntityName () + "Mapper" + ".xml" }}); cfg.setFileOutConfigList (focList); mpg.setCfg (cfg); mpg.setTemplate (new TemplateConfig (). SetXml (null)); / / StrategyConfig strategy = new StrategyConfig (); strategy.setNaming (NamingStrategy.underline_to_camel); strategy.setColumnNaming (NamingStrategy.underline_to_camel); strategy.setEntityLombokModel (true) / / set the logical delete key strategy.setLogicDeleteFieldName ("deleted"); / / TODO specifies the database table name of the generated bean strategy.setInclude ("trade_coupon"); / / strategy.setSuperEntityColumns ("id"); / / hump hyphen strategy.setControllerMappingHyphenStyle (true); mpg.setStrategy (strategy) / / to select a freemarker engine, you need to specify the following. Note that there must be pom dependencies! Mpg.setTemplateEngine (new FreemarkerTemplateEngine ()); mpg.execute ();}} how to write the sample code about SpringBoot integrating Mybatis-plus and realizing automatic generation of related files is shared here. I hope the above content can be helpful to everyone and learn more knowledge. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report