Spring boot is a new thing for me. During my learning process, I found that this thing is still easy to get started. When Spring boot is not configured, it will use Spring data jpa by default. This thing can be said to be a very simple tool, but I still prefer to use mybatis. There is no best tool, only this one is suitable for me.
Speaking of mybatis, there is a very useful tool recently - mybatis-Plus (official website). The updated version is now 2.1.2, and this version is also used here. My favorite features are code generators and conditional constructors, so that they can be developed more easily.
There is a Spring boot example on the official website of mybatisPlus. I followed it and the program did not run. Later I found out that the H2 database used by demo is not the same as mysql. So if you want to integrate mybatisPlus, you can do not look at the official website and avoid detours.
The following is the integration process
1. First, you need to get all the required jar files. The things you need for pom.xml are as follows
pom.xml(incomplete)
<!-- mybatis-plus begin --><dependency> <groupId>com.baomidou</groupId> <artifactId>mybatisplus-spring-boot-starter</artifactId> <version>1.0.4</version></dependency><dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus</artifactId> <version>2.1.2</version></dependency><dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId></dependency><!-- mybatis-plus end --><!-- druid Alibaba database connection pool--><dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.3</version></dependency><!--mysql--><dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope></dependency><dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.1</version></dependency>
2. Add mybatis-related configurations, such as account, password, etc. Here I used application.yml to match.
application.yml
server: port: 8080#springspring: devtools: restart: enabled: true #This is for hot deployment, and it is not related to mybatis#DATABASE CONFIG datasource: driver-class-name: com.mysql.jdbc.Driver username: root password: root url: jdbc:mysql://mysqldb:3306/tdx_shop?useUnicode=true&characterEncoding=utf-8 type: com.alibaba.druid.pool.DruidDataSource #Here is configuring the druid connection pool. The following are all configuration information for druid filters: stat,wall,log4j maxActive: 20 initialSize: 1 maxWait: 60000 minIdle: 1 timeBetweenEvictionRunsMillis: 60000 minEvictableIdleTimeMillis: 300000 validationQuery: select 'x' testWhileIdle: true testOnBorrow: false testOnReturn: false poolPreparedStatements: true maxOpenPreparedStatements: 20 connection-properties: druid.stat.merggSql=ture;druid.stat.slowSqlMillis=5000#mybatismybatis: mapper-locations: classpath*:/mapper/**Mapper.xml #Put the xml file in com.XX.mapper.* may have problems found. Here is the mapper under resource #Entity scan, multiple packages are separated by commas or semicolons. TypeAliasesPackage: com.tdx.account_service.entity #This is the location of the entity class configuration: map-underscore-to-camel-case: true cache-enabled: false#logginglogging: level: warn
The configuration stuff is similar to what we used to configure with mybatis, but spring boot does not have an XML configuration file. Pay attention to the content of the red letter, there is basically no problem.
3. Mybatis-Plus configuration file------MybatisPlusConfig. First, let’s explain the file path in the figure above. Among them, MybatisPlusConfig is placed in the config folder, while the xml file is placed in the mapper under Resouces.
Then there is the MybatisPlusConfig content part
MybatisProperties.java
package com.tdx.account_service.config;import com.alibaba.druid.pool.DruidDataSource;import com.alibaba.druid.support.http.StatViewServlet;import com.alibaba.druid.support.http.WebStatFilter;import com.baomidou.mybatisplus.MybatisConfiguration;import com.baomidou.mybatisplus.MybatisConfiguration;import com.baomidou.mybatisplus.entity.GlobalConfiguration;import com.baomidou.mybatisplus.enums.DBType;import com.baomidou.mybatisplus.plugins.PaginationInterceptor;import com.baomidou.mybatisplus.plugins.PerformanceInterceptor;import com.baomidou.mybatisplus.plugins.parser.ISqlParser;import com.baomidou.mybatisplus.plugins.parser.ISqlParserFilter;import com.baomidou.mybatisplus.plugins.parser.tenant.TenantHandler;import com.baomidou.mybatisplus.plugins.parser.tenant.TenantSqlParser;import com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean;import com.baomidou.mybatisplus.spring.boot.starter.SpringBootVFS;import com.baomidou.mybatisplus.toolkit.PluginUtils;import net.sf.jsqlparser.expression.Expression;import net.sf.jsqlparser.expression.LongValue;import org.apache.ibatis.mapping.DatabaseIdProvider;import org.apache.ibatis.mapping.MappedStatement;import org.apache.ibatis.plugin.Interceptor;import org.apache.ibatis.reflection.MetaObject;import org.mybatis.spring.annotation.MapperScan;import org.mybatis.spring.boot.autoconfigure.MybatisProperties;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.bind.RelaxedPropertyResolver;import org.springframework.boot.context.properties.EnableConfigurationProperties;import org.springframework.boot.web.servlet.FilterRegistrationBean;import org.springframework.boot.web.servlet.ServletRegistrationBean;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.core.env.Environment;import org.springframework.core.io.DefaultResourceLoader;import org.springframework.core.io.ResourceLoader;import org.springframework.util.ObjectUtils;import org.springframework.util.StringUtils;import javax.sql.DataSource;import java.sql.SQLException;import java.util.ArrayList;import java.util.List;/** * code is far away from bug with the animal protecting * ┏┓ ┏┓ * ┏┛━━━━━┛┻┓ * ┃ ┃ * ┃ ━ ┃ * ┃ ━ ┃ * ┃ ┳┛ ┗┳ ┃ * ┃ ┃ * ┃ ┃ * ┃ ┗┳ ┃ * ┃ ┃ * ┃ ┗┓ ┏━┛ * ┃ ┃ ┃ Bless of the beast* ┃ ┃ ┃ ┃ ┃ ┃ ┗┓ ┏┛ * ┃ ┃ ┃ Bless of the beast* ┃ ┃ ┃ ┃ ┃ ┃ No bugs! * ┃ ┗━━━┓ * ┃ ┣┓ * ┃ ┏┛ * ┗┓┓┏━┳┓┏┛ * ┃┫┫ ┃┫┫ * ┗┻┛ ┗┻┛ * * @Description : MybatisPlus Configuration* ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- class MybatisPlusConfig { @Autowired private Environment environment; private RelaxedPropertyResolver propertyResolver; @Autowired private DataSource dataSource; @Autowired private MybatisProperties properties; @Autowired private ResourceLoader resourceLoader = new DefaultResourceLoader(); @Autowired(required = false) private Interceptor[] interceptors; @Autowired(required = false) private DatabaseIdProvider databaseIdProvider; /** * @Description : mybatis-plus SQL execution efficiency plug-in [can be closed in production environment] * --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */ @Bean public DataSource druidDataSource() throws SQLException { this.propertyResolver = new RelaxedPropertyResolver(environment, "spring.datasource."); System.out.println("========================================================================================================================================================================================================================================================================================================================================================================================================================================================== datasource.setUrl(propertyResolver.getProperty("url")); datasource.setDriverClassName(propertyResolver.getProperty("driver-class-name")); datasource.setUsername(propertyResolver.getProperty("username")); datasource.setPassword(propertyResolver.getProperty("password")); datasource.setInitialSize(Integer.valueOf(propertyResolver.getProperty("initial-size"))); datasource.setMinIdle(Integer.valueOf(propertyResolver.getProperty("min-idle"))); datasource.setMaxWait(Long.valueOf(propertyResolver.getProperty("max-wait"))); datasource.setMaxActive(Integer.valueOf(propertyResolver.getProperty("max-active"))); datasource.setMinEvictableIdleTimeMillis(Long.valueOf(propertyResolver.getProperty("min-evictable-idle-time-millis"))); try { datasource.setFilters(propertyResolver.getProperty("filters")); } catch (SQLException e) { e.printStackTrace(); } return datasource; } /** * @Description : mybatis-plus pagination plugin* -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- : Create in 2017/9/19 13:59 */ @Bean public PaginationInterceptor paginationInterceptor() { PaginationInterceptor page = new PaginationInterceptor(); page.setDialectType("mysql"); return page; } /** * All resources that have been automatically loaded are used here. Don't specify the configuration file manually and the configuration file of mybatis-boot* @return */ @Bean public MybatisSqlSessionFactoryBean mybatisSqlSessionFactoryBean() { MybatisSqlSessionFactoryBean mybatisPlus = new MybatisSqlSessionFactoryBean(); mybatisPlus.setDataSource(dataSource); mybatisPlus.setVfs(SpringBootVFS.class); if (StringUtils.hasText(this.properties.getConfigLocation())) { mybatisPlus.setConfigLocation(this.resourceLoader.getResource(this.properties.getConfigLocation())); } mybatisPlus.setConfiguration(properties.getConfiguration()); if (!ObjectUtils.isEmpty(this.interceptors)) { mybatisPlus.setPlugins(this.interceptors); } // MP global configuration, enter the class to see the comments GlobalConfiguration globalConfig = new GlobalConfiguration(); globalConfig.setDbType(DBType.MYSQL.name()); // ID Policy AUTO->`0`("Database ID self-increment") INPUT->`1`(User input ID") ID_WORKER->`2`("Global Unique ID") UUID->`3`("Global Unique ID") globalConfig.setIdType(2); mybatisPlus.setGlobalConfig(globalConfig); MybatisConfiguration mc = new MybatisConfiguration(); mc.setDefaultScriptingLanguage(MybatisXMLLanguageDriver.class); mybatisPlus.setConfiguration(mc); if (this.databaseIdProvider != null) { mybatisPlus.setDatabaseIdProvider(this.databaseIdProvider); } if (StringUtils.hasLength(this.properties.getTypeAliasesPackage()))) { mybatisPlus.setTypeAliasesPackage(this.properties.getTypeAliasesPackage()); } if (StringUtils.hasLength(this.properties.getTypeAliasesPackage()); } if (StringUtils.hasLength(this.properties.getTypeHandlersPackage())) { mybatisPlus.setTypeHandlersPackage(this.properties.getTypeHandlersPackage()); } if (!ObjectUtils.isEmpty(this.properties.resolveMapperLocations())) { mybatisPlus.setMapperLocations(this.properties.resolveMapperLocations()); } return mybatisPlus; } /** * Register a StatViewServlet * @return */ @Bean public ServletRegistrationBean DruidStatViewServle(){ //org.springframework.boot.context.embedded.ServletRegistrationBean provides the class for registration. ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*"); //Add initialization parameters: initParams //Whitelist: // servletRegistrationBean.addInitParameter("allow","127.0.0.1"); //IP blacklist (when there is a commonality, deny takes precedence over allow) : If deny is satisfied, prompt: Sorry, you are not allowed to view this page. // servletRegistrationBean.addInitParameter("deny","192.168.1.73"); //Login the account password to view the information. servletRegistrationBean.addInitParameter("loginUsername","root"); servletRegistrationBean.addInitParameter("loginPassword","root"); //Is it possible to reset the data? servletRegistrationBean.addInitParameter("resetEnable","false"); return servletRegistrationBean; } /** * Register one: filterRegistrationBean * * @return */ @Bean public FilterRegistrationBean druidStatFilter(){ FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter()); //Add filter rules. filterRegistrationBean.addUrlPatterns("/*"); //Add format information that does not need to be ignored. filterRegistrationBean.addInitParameter("exclusions","*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"); return filterRegistrationBean; }}Here is the complete configuration file. It is important to note that the packages introduced are not incorrect!
4. You also need to enable dao scanning. It is very simple. Add @MapperScan("com.tdx.account_service.dao*") to the startup file. The following is the complete one.
At this point, the configuration has been completed, and you can run the project after running it.
I think Mybatis-Plus is the most fun part of the code generator. The following is the process of using the code generator
Add something to pom.xml
<dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity-engine-core</artifactId> <version>2.0</version></dependency>
1. Code generator configuration file
MybatisPlusConfig.java
/** * Copyright (c) 2011-2016, hubin ([email protected]). * <p> * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */package com.tdx.account_service.generator;import java.io.File;import java.util.ArrayList;import java.util.Collections;import java.util.HashMap;import java.util.List;import java.util.Map;import com.baomidou.mybatisplus.enums.FieldFill;import com.baomidou.mybatisplus.generator.AutoGenerator;import com.baomidou.mybatisplus.generator.InjectionConfig;import com.baomidou.mybatisplus.generator.config.DataSourceConfig;import com.baomidou.mybatisplus.generator.config.FileOutConfig;import com.baomidou.mybatisplus.generator.config.GlobalConfig;import com.baomidou.mybatisplus.generator.config.PackageConfig;import com.baomidou.mybatisplus.generator.config.StrategyConfig;import com.baomidou.mybatisplus.generator.config.TemplateConfig;import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;import com.baomidou.mybatisplus.generator.config.po.TableFill;import com.baomidou.mybatisplus.generator.config.po.TableInfo;import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;import com.baomidou.mybatisplus.generator.config.rules.DbType;import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;/** *code is far away from bug with the animal protecting * ┏┓ ┏┓ *┏┛━━━━━━━┛┻┓ *┃ ┃ *┃ ━ ┃ *┃ ┳┛ ┗┳ ┃ *┃ ┃ *┃ ┃ *┃ ┃ *┗━┓ ┏━┛ * ┃ ┃ ┃ Bless the beast* ┃ ┃ ┃ ┃ code without bugs! * ┃ ┗━━━┓ * ┃ ┣┓ * ┃ ┏┛ * ┗┓┓┏━┳┓┏┛ * ┃┫┫ ┃┫┫ * ┗┻┛ ┗┻┛ * * @Description : MybatisPlus Code Generator* ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- packageName="account_service"; //File path private static String authorName="Liang.Guangqing"; //Author private static String table="sc_user"; //table name private static String prefix="sc_"; //table prefix private static File file file = new File(packageName); private static String path = file.getAbsolutePath(); public static void main(String[] args) { // Customize the fields that need to be filled List<TableFill> tableFillList = new ArrayList<>(); tableFillList.add(new TableFill("ASDD_SS", FieldFill.INSERT_UPDATE)); // Code Generator AutoGenerator mpg = new AutoGenerator().setGlobalConfig( // Global configuration new GlobalConfig() .setOutputDir(path+"/src/main/java")// Output directory.setFileOverride(true)// Whether to overwrite the file.setActiveRecord(true)// Enable activeRecord mode.setEnableCache(false)// XML Secondary cache.setBaseResultMap(true)// XML ResultMap .setBaseColumnList(true)// XML columnList .setOpen(false)// Open the folder after generation.setAuthor(authorName) // Customize the file name, note that %s will automatically fill the table entity attributes! .setMapperName("%sMapper") .setXmlName("%sMapper") .setServiceName("%sService") .setServiceImplName("%sServiceImpl") .setControllerName("%sController") ).setDataSource( // Data source configuration new DataSourceConfig() .setDbType(DbType.MYSQL)// Database type.setTypeConvert(new MySqlTypeConvert() { // Customize database table field type conversion [optional] @Override public DbColumnType processTypeConvert(String fieldType) { System.out.println("Conversion type: " + fieldType); // if ( fieldType.toLowerCase().contains( "tinyint" ) ) { // return DbColumnType.BOOLEAN; // } return super.processTypeConvert(fieldType); } }) .setDriverName("com.mysql.jdbc.Driver") .setUsername("root") .setPassword("root") .setUrl("jdbc:mysql://127.0.0.1:3306/tdx_shop?characterEncoding=utf8") ).setStrategy( // Policy Configuration new StrategyConfig() // .setCapitalMode(true)// Global capitalization naming //.setDbColumnUnderline(true)//Global underscore naming.setTablePrefix(new String[]{prefix})// Here you can modify it to your table prefix.setNaming(NamingStrategy.underline_to_camel)// Table name generation strategy.setInclude(new String[] { table }) // Table that needs to be generated.setRestControllerStyle(true) //.setExclude(new String[]{"test"}) // Exclude the generated table // Custom entity parent class // .setSuperEntityClass("com.baomidou.demo.TestEntity") // Custom entity, public field //.setSuperEntityColumns(new String[]{"test_id"}) .setTableFillList(tableFillList) // Custom mapper parent class // .setSuperMapperClass("com.baomidou.demo.TestMapper") // Custom service parent class // .setSuperServiceClass("com.baomidou.demo.TestService") // Custom service implementation class parent class // .setSuperServiceImplClass("com.baomidou.demo.TestServiceImpl") // Custom controller Parent class .setSuperControllerClass("com.tdx."+packageName+".controller.AbstractController") // [Entity] Whether to generate field constants (default false) // public static final String ID = "test_id"; // .setEntityColumnConstant(true) // [Entity] Is the builder model (default false) // public User setName(String name) {this.name = name; return this;} // .setEntityBuilderModel(true) // [Entity] Is the lombok model (default false) <a href="https://projectlombok.org/" rel="external nofollow" >document</a> // .setEntityLombokModel(true) // Whether to remove is prefix from the Boolean type field // .setEntityBooleanColumnRemoveIsPrefix(true) // .setRestControllerStyle(true) // .setControllerMappingHyphenStyle(true) ).setPackageInfo( // PackageConfig() // .setModuleName("User") .setParent("com.tdx."+packageName)// Custom package path.setController("controller")// Here is the controller package name, default web .setEntity("entity") .setMapper("dao") .setService("service") .setServiceImpl("service.impl") //.setXml("mapper") ).setCfg( // Inject custom configuration, you can use the value set by cfg.abc in VM new InjectionConfig() { @Override public void initMap() { Map<String, Object> map = new HashMap<>(); map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-mp"); this.setMap(map); } }.setFileOutConfigList(Collections.<FileOutConfig>singletonList(new FileOutConfig("/templates/mapper.xml.vm") { // Custom output file directory @Override public String outputFile(TableInfo tableInfo) { return path+"/src/main/resources/mapper/" + tableInfo.getEntityName() + "Mapper.xml"; } })) ).setTemplate( // Turn off the default xml generation and adjust the generation to the root directory new TemplateConfig().setXml(null) // Customize the template configuration. The template can refer to the source code /mybatis-plus/src/main/resources/template Use copy // Go to your project src/main/resources/template directory. The template name can also be customized as follows: // .setController("..."); // .setEntity("..."); // .setMapper("..."); // .setXml("..."); // .setXml("..."); // .setService("..."); // .setServiceImpl("..."); ); // Execute to generate mpg.execute(); // Print injection settings, here demonstrate how to get the injection content in the template [noble] System.err.println(mpg.getCfg().getMap().get("abc")); }}
There are still many modifications in the file. The most important thing is the connection information of mysql. There is no reason why your account and password are wrong. You can connect to it. Secondly, set the path of the template file you generated. The path I generated here can be seen in the figure above. It is under com.tdx.account_service. Note that the xml file should be placed under resources, otherwise it will be recognized and said that this method cannot be found.
The files generated according to the official website's code template are basically blank. The main reason is that mybatis-Plus integrates public methods, and many commonly used tools can be referenced. Here I provide the Controller.java.vm file I modified, mainly according to my own habits.
controller.java.vm
package ${package.Controller};import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;#if(${restControllerStyle})import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RestController;#elseimport org.springframework.steretype.Controller;#end#if(${superControllerClassPackage})import ${superControllerClassPackage};#endimport org.springframework.beans.factory.annotation.Autowired;import com.baomidou.mybatisplus.mapper.EntityWrapper;import com.baomidou.mybatisplus.plugins.Page;import ${package.Service}.${table.serviceName};import ${package.Entity}.common.DatatablesJSON;import ${package.Entity}.common.JSONResult;import ${package.Entity}.${entity};import org.slf4j.Logger;import org.slf4j.LoggerFactory;/** *code is far away from bug with the animal protecting * ┏┓ ┏┓ *┏┛━━━━┛┻┓ *┃ ┃ *┃ ┳┛ ┗┳ ┃ *┃ ┃ *┃ ┃ *┃ ┗┳ ┃ *┃ ┃ *┃ ┗┳ ┃ *┃ ┃ *┃ ┗┓ ┏━┛ * ┃ ┃ *┃ ┃ *┗┓ ┏━┛ * ┃ ┃ ┃ *┃ ┃ *┗┓ ┏━┛ * ┃ ┃ Blessing* ┃ ┃The code has no bugs! * ┃ ┗━━━┓ * ┃ ┣┓ * ┃ ┏┛ * ┗┓┓┏━┳┓┏┛ * ┃┫┫┃┫ * ┗┻┛ ┗┻┛ * * @description : ${entity} Controller* ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ */#if(${restControllerStyle})@RestController#else@Controller#end@RequestMapping("#if(${package.ModuleName})/${package.ModuleName}#end/#if(${controllerMappingHyphenStyle})${controllerMappingHyphen}#else${table.entityPath}#end")#if(${superControllerClass})public class ${table.controllerName} extends ${superControllerClass} {#elsepublic class ${table.controllerName} {#end private final Logger logger = LoggerFactory.getLogger(${table.controllerName}.class); @Autowired public ${table.serviceName} ${table.entityPath}Service; /** * @description : Get the paging list* --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- RequestMethod.POST) public Object get${entity}List(${entity} param , @RequestParam(value = "draw",defaultValue = "0") Integer draw, @RequestParam(value = "length") Integer length, @RequestParam(value = "start") Integer start) { DatatablesJSON<${entity}> resJson=new DatatablesJSON<>(); try { Integer pageNo=getPageNo(start,length); Page<${entity}> page=new Page<${entity}>(pageNo,length); ${table.entityPath}Service.selectPage(page,new EntityWrapper<${entity}>(param)); resJson.setDraw(draw++); resJson.setRecordsTotal(page.getTotal()); resJson.setRecordsFiltered(page.getTotal()); resJson.setData(page.getRecords()); resJson.setSuccess(true); }catch (Exception e){ resJson.setSuccess(false); resJson.setError("Exception information:{"+e.getClass().getName()+"}"); logger.info("Exception information:{}"+e.getMessage()); } return resJson; } /** * @description : Get ${entity} by id * -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Object get${entity}ById(String id) { JSONResult<${entity}> resJson = new JSONResult<>(); try { ${entity} param= ${table.entityPath}Service.selectById(id); resJson.setData(param); resJson.setSuccess(true); }catch (Exception e) { resJson.setSuccess(false); resJson.setMessage("Exception information: {"+e.getClass().getName()+"}"); logger.info("Exception information:{}"+e.getMessage()); } return resJson; } /** * @description : Delete ${entity} by id * ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ JSONResult<>(); try{ resJson.setSuccess(${table.entityPath}Service.deleteById(id)); }catch (Exception e) { resJson.setSuccess(false); resJson.setMessage("Exception information:{"+e.getClass().getName()+"}"); logger.info("Exception information:{}"+e.getMessage()); } return resJson; } /** * @description : Update ${entity} by id * -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- @since : Create in ${date} */ @RequestMapping(value = "/update${entity}ById",method = RequestMethod.POST) public Object update${entity}ById(${entity}param) { JSONResult<${entity}> resJson = new JSONResult<>(); try{ resJson.setSuccess(${table.entityPath}Service.updateById(param)); }catch (Exception e) { resJson.setSuccess(false); resJson.setMessage("Exception information:{"+e.getClass().getName()+"}"); logger.info("Exception information:{}"+e.getMessage()); } return resJson; } /** * @description : Add ${entity} * ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- param) { JSONResult<${entity}> resJson = new JSONResult<>(); try{ resJson.setSuccess(${table.entityPath}Service.insert(param)); }catch (Exception e) { resJson.setSuccess(false); resJson.setMessage("Exception information: {"+e.getClass().getName()+"}"); logger.info("Exception information: {}"+e.getMessage()); } return resJson; }}In addition to this file, I follow the official website of the other code templates. Here I refer to 3 external files, including AbstractController.java (controller base class), DatatablesJSON.java and JSONResult.java. Then these files refer to other files. I was confused. Why are there so many files? It seems that if all of them are posted, it will take up more space. So I chose to believe in Code Cloud. If you need it, please download the code cloud according to the few files on Code Cloud. It should be noted that my templates are directly replaced by the templates directory in mybatis-plus.jar.
Finally, it's the test process
The following code snippets are placed in the Controller file, and then the program is started, corresponding to the port, and request method. For testing, you need to operate according to your own entity class, so it is for reference only.
/** * Pagination PAGE */ @GetMapping("/test") public Page<User> test() { return userService.selectPage(new Page<User>(0, 12)); } /** * AR partial test*/ @GetMapping("/test1") public Page<User> test1() { User user = new User(); System.err.println("Delete all:" + user.delete(null)); //user.setId(2017091801L); user.setAccout("test"+num++); user.setType("test"); user.setCreateTime(new Date()); user.setPhone("13111110000"); user.setPassword("123456"); user.setNickname("guangqing"+2*num++); user.insert(); System.err.println("Query insert result: " + user.selectById().toString()); //user.setNickname("mybatis-plus-ar"); System.err.println("Update:" + user.updateById()); return user.selectPage(new Page<User>(0, 12), null); } /** * Add, delete, modify and check CRUD */ @GetMapping("/test2") public User test2() { User user = new User(); user.setId(123456L); user.setAccout("test"); user.setType("test"); user.setCreateTime(new Date()); user.setPhone("13111110000"); user.setPassword("123456"); user.setNickname("guangqing"); System.err.println("Delete a data: " + userService.deleteById(1L)); System.err.println("Insert a data: " + userService.insert(user)); User user2 = new User(); user.setId(223456L); user.setAccout("test2"); user.setType("test"); user.setCreateTime(new Date()); user.setPhone("13111110000"); user.setPassword("123456"); user.setNickname("guangqing"); boolean result = userService.insert(user); // Automatic writeback ID Long id = user.getId(); System.err.println("Insert a piece of data: " + result + ", Insert information: " + user.toString()); System.err.println("Query: " + userService.selectById(id).toString()); Page<User> userListPage = userService.selectPage(new Page<User>(1, 5), new EntityWrapper<>(new User())); System.err.println("total=" + userListPage.getTotal() + ", current list size=" + userListPage.getRecords().size()); return userService.selectById(1L); } @GetMapping("testSelect") public Object testSelect() { Integer start = 0; Integer length =10; User param = new User(); //param.setNickname("guangqing2"); Integer pageNo=getPageNo(start,length); Page<User> page =new Page<User>(pageNo,length); EntityWrapper<User> ew = new EntityWrapper<User>(); ew.setEntity(param); ew.where("password={0}","123456") .like("nickname","guangqing") .ge("create_time","2017-09-21 15:50:00"); userService.selectPage(page, ew); DatatablesJSON<User> resJson= new DatatablesJSON<>(); //resJson.setDraw(draw++); resJson.setRecordsTotal(page.getTotal()); resJson.setRecordsFiltered(page.getTotal()); resJson.setData(page.getRecords()); return resJson; } @GetMapping("/selectsql") public Object getUserBySql() { JSONObject result = new JSONObject(); result.put("records", userService.selectListBySQL()); return result; } /** * 7. Pagination size Number of displays on one page Current page number* Method 1: http://localhost:8080/user/page?size=1¤t=1<br> * Method 2: http://localhost:8080/user/pagehelper?size=1¤t=1<br> * / // Parameter mode pagination @GetMapping("/page") public Object page(Page page) { return userService.selectPage(page); } // ThreadLocal Pattern pagination @GetMapping("/pagehelper") public Object pagehelper(Page page) { PageHelper.setPagination(page); page.setRecords(userService.selectList(null)); page.setTotal(PageHelper.freeTotal());//Get the total number and free resources. PageHelper.getTotal() return page; } /** * Test things* http://localhost:8080/user/test_transactional<br> * Access the following and no data is found to indicate that things are reliable! ! <br> * http://localhost:8080/user/test<br> * <br> * Start Application Add @EnableTransactionManagement The annotation seems to be enabled without default<br> * Methods that require things plus @Transactional is a must! ! */ @Transactional @GetMapping("/test_transactional") public void testTransactional() { //userService.insert(new User(1000L, "Test Things", 16, 3)); System.out.println("Exception is thrown manually here and data is automatically rolled back"); throw new RuntimeException(); }With so many tests, I think the most interesting thing is the conditional constructor, which has a more complete official website, and I wrote it according to my own needs.
Finally, thank you for watching. Please forgive me for not writing well if you don’t have enough experience in blogging. If you can help you, please give me a thumbs up. If you encounter something you don’t understand, or if I have any mistakes, please give it a comment! I also hope everyone will support Wulin.com more.