Mybatis-Plus (MP for short) is a Mybatis enhancement tool. Based on Mybatis, it only enhances and does not change, and is born to simplify development and improve efficiency.
Chinese document: http://baomidou.oschina.io/mybatis-plus-doc/#/
This article introduces
1) How to build it
2) Code generation (controller, service, mapper, xml)
3) The CRUD, conditional query, and pagination base classes of a single table have been done for you
1. How to build it
1. First we create a springboot project --> https://start.spring.io/
2. maven dependency
<dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>2.3</version> </dependency> <!-- velocity dependency for code generation --> <dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity-engine-core</artifactId> <version>2.0</version> </dependency>
3. Configuration (because I feel it's too wordy, the configuration of the data source is omitted here)
application.properties
mybatis-plus.mapper-locations=classpath:/mapper/*Mapper.xmlmybatis-plus.typeAliasesPackage=com.taven.web.springbootmp.entitymybatis-plus.global-config.id-type=3mybatis-plus.global-config.field-strat egy=2mybatis-plus.global-config.db-column-underline=truemybatis-plus.global-config.key-generator=com.baomidou.mybatisplus.incrementer.OracleKeyGeneratormybatis-plus.global-config.logic-delete-value=1 mybatis-plus.global-config.logic-not-delete-value=0mybatis-plus.global-config.sql-injector=com.baomidou.mybatisplus.mapper.LogicSqlInjector#This needs to be changed to your class mybatis-plus.global-config.meta-object-handler=com .taven.web.springbootmp.MyMetaObjectHandlermybatis-plus.configuration.map-underscore-to-camel-case=truemybatis-plus.configuration.cache-enabled=falsemybatis-plus.configuration.jdbc-type-for-null=null
Configuration class MybatisPlusConfig
import org.mybatis.spring.annotation.MapperScan;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import com.baomidou.mybatisplus.incrementer.H2KeyGenerator;import com.baomidou.mybatisplus.incrementer.IKeyGenerator;import com.baomidou.mybatisplus.mapper.ISqlInjector;import com.baomidou.mybatisplus.mapper.LogicSqlInjector;import com.baomidou.mybatisplus.mapper.MetaObjectHandler;import com.baomidou.mybatisplus.plugins.PaginationInterceptor;import com.baomidou.mybatisplus.plugins.PerformanceInterceptor;import com.taven.web.springbootmp.MyMetaObjectHandler;@EnableTransactionManagement@Configuration@MapperScan("com.taven.web.springbootmp.mapper")public class MybatisPlusConfig { /** * mybatis-plus SQL execution efficiency plug-in [can be closed in production environment] */ @Bean public PerformanceInterceptor performanceInterceptor() { return new PerformanceInterceptor(); } /* * Pagination plug-in, automatically identifying multi-tenants in database type, please refer to the official website [Plugin Extension] */ @Bean public PaginationInterceptor paginationInterceptor() { return new PaginationInterceptor(); } @Bean public MetaObjectHandler metaObjectHandler() { return new MyMetaObjectHandler(); } /** * Injection primary key generator*/ @Bean public IKeyGenerator keyGenerator() { return new H2KeyGenerator(); } /** * Injection sql injector*/ @Bean public ISqlInjector sqlInjector() { return new LogicSqlInjector(); }} import com.baomidou.mybatisplus.mapper.MetaObjectHandler;import org.apache.ibatis.reflection.MetaObject;import org.slf4j.Logger;import org.slf4j.LoggerFactory;/** * Inject public fields automatically fill, optional injection method *///@Componentpublic class MyMetaObjectHandler extends MetaObjectHandler { protected final static Logger logger = LoggerFactory.getLogger(Application.class); @Override public void insertFill(MetaObject metaObject) { logger.info("Do something undescribable when added"); } @Override public void updateFill(MetaObject metaObject) { logger.info("Do something undescribable when updated"); }} 2. Code generation
Execute junit to generate controller, service interface, implementation, mapper and xml
import org.junit.Test;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;import com.baomidou.mybatisplus.generator.config.rules.DbType;import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;/** * <p> * Test generation code* </p> * * @author K God* @date 2017/12/18 */public class GeneratorServiceEntity { @Test public void generateCode() { String packageName = "com.taven.web.springbootmp"; boolean serviceNameStartWithI = false;//user -> UserService, set to true: user -> IUserService generateByTables(serviceNameStartWithI, packageName, "cable", "station");//Modify to your table name} private void generateByTables(boolean serviceNameStartWithI, String packageName, String... tableNames) { GlobalConfig config = new GlobalConfig(); String dbUrl = "jdbc:mysql://localhost:3306/communicate"; DataSourceConfig dataSourceConfig = new DataSourceConfig(); dataSourceConfig.setDbType(DbType.MYSQL) .setUrl(dbUrl) .setUsername("root") .setPassword("root") .setDriverName("com.mysql.jdbc.Driver"); StrategyConfig strategyConfig = new StrategyConfig(); strategyConfig .setCapitalMode(true) .setEntityLombokModel(false) .setDbColumnUnderline(true) .setNaming(NamingStrategy.underline_to_camel) .setInclude(tableNames);//Modify and replace with the table name you need, pass multiple table names to array config.setActiveRecord(false) .setEnableCache(false) .setAuthor("Yin Tianwen") .setOutputDir("E://dev//stsdev//spring-boot-mp//src//main//java") .setFileOverride(true); if (!serviceNameStartWithI) { config.setServiceName("%sService"); } new AutoGenerator().setGlobalConfig(config) .setDataSource(dataSourceConfig) .setStrategy(strategyConfig) .setPackageInfo( new PackageConfig() .setParent(packageName) .setController("controller") .setEntity("entity") ).execute(); }// private void generateByTables(String packageName, String... tableNames) {// generateByTables(true, packageName, tableName);// }}The construction has been basically completed at this point, and you can start using it below!
3. Use Mybatis-Plus
First, we execute the generatedCode() above and generate the following code for us based on the table structure (the xml was moved to the following manually). The service and mapper have inherited the base class and encapsulated many methods for us. Let’s see a few simple examples below.
/** * <p> * Front-end controller* </p> * * @author Yin Tianwen* @since 2018-05-31 */@Controller@RequestMapping("/cable")public class CableController { @Autowired private CableService cableService; /** * list query test* */ @RequestMapping("/1") @ResponseBody public Object test1() { // Construct the EntityWrapper object corresponding to the entity and filter and query EntityWrapper<Cable> ew = new EntityWrapper<>(); ew.where("type={0}", 1) .like("name", "king") .and("core_number={0}", 24) .and("is_delete=0"); List<Cable> list = cableService.selectList(ew); List<Map<String, Object>> maps = cableService.selectMaps(ew); System.out.println(list); System.out.println(maps); return "ok"; } /** * Pagination query test*/ @RequestMapping("/2") @ResponseBody public Object test2() { // Construct the EntityWrapper object corresponding to the entity and perform filtering query EntityWrapper<Cable> ew = new EntityWrapper<>(); ew.where("type={0}", 1)// .like("name", "king") .and("core_number={0}", 24) .and("is_delete=0"); Page<Cable> page = new Page<>(1,10); Page<Cable> pageRst = cableService.selectPage(page, ew); return pageRst; } /** * Custom query field*/ @RequestMapping("/3") @ResponseBody public Object test3() { Object vl = null; // Construct the EntityWrapper object corresponding to the entity and perform filtering query EntityWrapper<Cable> ew = new EntityWrapper<>(); ew.setSqlSelect("id, `name`, " + "case type/n" + "when 1 then '220kv'/n" + "end typeName") .where("type={0}", 1)// .like("name", "king") .where(false, "voltage_level=#{0}", vl);//When vl is empty, Page<Cable> page = new Page<>(1,10); Page<Cable> pageRst = cableService.selectPage(page, ew); return pageRst; } /** * insert */ @RequestMapping("/4") @ResponseBody public Object test4() { Cable c = new Cable(); c.setName("test optical cable"); cableService.insert(c); return "ok"; } /** * update */ @RequestMapping("/5") @ResponseBody public Object test5() { Cable c = cableService.selectById(22284l); c.setName("test optical cable 2222"); c.setType(1); cableService.updateById(c); return "ok"; } }The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.