搭建一个MP-demo(mybatis_plus)
MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
搭建一个简单的MP-demo
1.配置pom.xml
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!-- mybatis的orm插件 --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatisplus-spring-boot-starter</artifactId> <version>1.0.4</version> </dependency> <!-- mybatis plus --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus</artifactId> <version>2.0.7</version> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-core</artifactId> <version>3.1.0</version> <scope>test</scope> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.velocity/velocity --> <dependency> <groupId>org.apache.velocity</groupId> <artifactId>velocity</artifactId> <version>1.7</version> </dependency> <!-- https://mvnrepository.com/artifact/org.freemarker/freemarker --> <dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.28</version> </dependency> <!--数据库连接jdbc依赖--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <!--mysql链接依赖--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!--阿里druid数据库链接依赖--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.9</version> </dependency> <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>0.10.1</version> <scope>provided</scope> </dependency> </dependencies>
2.创建一个包config,再建两个class文件
DataSourceConfig.java
package com.demo.config; import com.alibaba.druid.pool.DruidDataSource; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import javax.sql.DataSource; /** * 数据源配置 */ @Configuration public class DataSourceConfig { @Bean(name = "dataSource") @ConfigurationProperties(prefix = "spring.datasource") public DataSource dataSource() { return new DruidDataSource(); } // 配置事物管理器 @Bean(name = "transactionManager") public DataSourceTransactionManager transactionManager() { return new DataSourceTransactionManager(dataSource()); } }
配置MybatisPlusConfig.Java
package com.demo.config; import com.baomidou.mybatisplus.plugins.PaginationInterceptor; import com.baomidou.mybatisplus.plugins.PerformanceInterceptor; import org.mybatis.spring.annotation.MapperScan; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; @Configuration //扫描dao或者是Mapper接口 @MapperScan("com.demo.mapper*") public class MybatisPlusConfig { /** * mybatis-plus 分页插件 */ @Bean public PaginationInterceptor paginationInterceptor() { PaginationInterceptor page = new PaginationInterceptor(); page.setDialectType("mysql"); return page; } /** * SQL执行效率插件 * 性能分析拦截器,用于输出每条 SQL 语句及其执行时间 */ @Bean @Profile({"dev", "pro"})// 设置 dev pro 环境开启 public PerformanceInterceptor performanceInterceptor() { return new PerformanceInterceptor(); } }
3.配置环境
application.properties
#默认启用开发环境配置
spring.profiles.active=dev
#启用生产环境配置
#spring.profiles.active=pro
application-dev.properties
server.port=666
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.url=jdbc:mysql://localhost:3306/eth
spring.datasource.username=root
spring.datasource.password=228197
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.max-idle=10
spring.datasource.max-wait=10000
spring.datasource.min-idle=5
spring.datasource.initial-size=5
mybatis-plus.mapper-locations=classpath:/mapper/*Mapper.xml
mybatis-plus.typeAliasesPackage=com.cn.restyle.entity
application-pro.properties
server.port=666
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.url=jdbc:mysql://localhost:3306/eth
spring.datasource.username=root
spring.datasource.password=228197
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.max-idle=10
spring.datasource.max-wait=10000
spring.datasource.min-idle=5
spring.datasource.initial-size=5
mybatis-plus.mapper-locations=classpath:/mapper/*Mapper.xml
mybatis-plus.typeAliasesPackage=com.cn.restyle.entity
4.在test目录下创建MpGenerator.Java,会在D盘下生成一个com的文件,将里面的entity,mapper,service,serviceimpl,controller,mapper.xml分别拷入工程对应的包内
package com.demo; import com.baomidou.mybatisplus.generator.AutoGenerator; import com.baomidou.mybatisplus.generator.InjectionConfig; import com.baomidou.mybatisplus.generator.config.*; import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert; import com.baomidou.mybatisplus.generator.config.rules.DbColumnType; import com.baomidou.mybatisplus.generator.config.rules.DbType; import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * <p> * 代码生成器演示 * </p> */ public class MpGenerator { final static String dirPath = "D://"; /** * <p> * MySQL 生成演示 * </p> */ public static void main(String[] args) { AutoGenerator mpg = new AutoGenerator(); // 选择 freemarker 引擎,默认 Veloctiy //mpg.setTemplateEngine(new FreemarkerTemplateEngine()); // 全局配置 GlobalConfig gc = new GlobalConfig(); gc.setOutputDir(dirPath); gc.setAuthor("jiangluo"); gc.setFileOverride(true); //是否覆盖 gc.setActiveRecord(true);// 不需要ActiveRecord特性的请改为false gc.setEnableCache(false);// XML 二级缓存 gc.setBaseResultMap(true);// XML ResultMap gc.setBaseColumnList(true);// XML columList // 自定义文件命名,注意 %s 会自动填充表实体属性! // gc.setMapperName("%sDao"); // gc.setXmlName("%sMapper"); // gc.setServiceName("MP%sService"); // gc.setServiceImplName("%sServiceDiy"); // gc.setControllerName("%sAction"); mpg.setGlobalConfig(gc); // 数据源配置 DataSourceConfig dsc = new DataSourceConfig(); dsc.setDbType(DbType.MYSQL); dsc.setTypeConvert(new MySqlTypeConvert() { // 自定义数据库表字段类型转换【可选】 @Override public DbColumnType processTypeConvert(String fieldType) { System.out.println("转换类型:" + fieldType); // 注意!!processTypeConvert 存在默认类型转换,如果不是你要的效果请自定义返回、非如下直接返回。 return super.processTypeConvert(fieldType); } }); dsc.setDriverName("com.mysql.jdbc.Driver"); dsc.setUsername("root"); dsc.setPassword("228197"); dsc.setUrl("jdbc:mysql://127.0.0.1:3306/eth?characterEncoding=utf8"); mpg.setDataSource(dsc); // 策略配置 StrategyConfig strategy = new StrategyConfig(); // strategy.setCapitalMode(true);// 全局大写命名 ORACLE 注意 strategy.setTablePrefix(new String[]{"tb_", "tsys_"});// 此处可以修改为您的表前缀 strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略 // strategy.setInclude(new String[] { "user" }); // 需要生成的表 // strategy.setExclude(new String[]{"test"}); // 排除生成的表 // 自定义实体父类 // strategy.setSuperEntityClass("com.baomidou.demo.TestEntity"); // 自定义实体,公共字段 // strategy.setSuperEntityColumns(new String[] { "test_id", "age" }); // 自定义 mapper 父类 // strategy.setSuperMapperClass("com.baomidou.demo.TestMapper"); // 自定义 service 父类 // strategy.setSuperServiceClass("com.baomidou.demo.TestService"); // 自定义 service 实现类父类 // strategy.setSuperServiceImplClass("com.baomidou.demo.TestServiceImpl"); // 自定义 controller 父类 // strategy.setSuperControllerClass("com.baomidou.demo.TestController"); // 【实体】是否生成字段常量(默认 false) // public static final String ID = "test_id"; // strategy.setEntityColumnConstant(true); // 【实体】是否为构建者模型(默认 false) // public User setName(String name) {this.name = name; return this;} strategy.setEntityBuilderModel(true); mpg.setStrategy(strategy); // 包配置 PackageConfig pc = new PackageConfig(); pc.setParent("com"); pc.setModuleName("demo"); pc.setController("controler"); pc.setEntity("entity"); pc.setMapper("mapper"); pc.setService("service"); pc.setServiceImpl("serviceImpl"); pc.setXml("mapperXml"); mpg.setPackageInfo(pc); // 注入自定义配置,可以在 VM 中使用 cfg.abc 【可无】 InjectionConfig cfg = new InjectionConfig() { @Override public void initMap() { Map<String, Object> map = new HashMap<String, Object>(); map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-mp"); this.setMap(map); } }; // 自定义 xxList.jsp 生成 List<FileOutConfig> focList = new ArrayList<FileOutConfig>(); /* focList.add(new FileOutConfig("/template/list.jsp.vm") { @Override public String outputFile(TableInfo tableInfo) { // 自定义输入文件名称 return "D://my_" + tableInfo.getEntityName() + ".jsp"; } }); cfg.setFileOutConfigList(focList); mpg.setCfg(cfg);*/ // 调整 xml 生成目录演示 /* focList.add(new FileOutConfig("/templates/mapper.xml.vm") { @Override public String outputFile(TableInfo tableInfo) { return dirPath + tableInfo.getEntityName() + "Mapper.xml"; } }); cfg.setFileOutConfigList(focList); */ mpg.setCfg(cfg); // 关闭默认 xml 生成,调整生成 至 根目录 /* TemplateConfig tc = new TemplateConfig(); tc.setXml(null); mpg.setTemplate(tc);*/ // 自定义模板配置,可以 copy 源码 mybatis-plus/src/main/resources/templates 下面内容修改, // 放置自己项目的 src/main/resources/templates 目录下, 默认名称一下可以不配置,也可以自定义模板名称 // TemplateConfig tc = new TemplateConfig(); // tc.setController("..."); // tc.setEntity("..."); // tc.setMapper("..."); // tc.setXml("..."); // tc.setService("..."); // tc.setServiceImpl("..."); // 如上任何一个模块如果设置 空 OR Null 将不生成该模块。 // mpg.setTemplate(tc); // 执行生成 mpg.execute(); // 打印注入设置【可无】 System.err.println(mpg.getCfg().getMap().get("abc")); } }
5.在test目录下建立一个测试类MPTest.java
package com.demo; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.demo.entity.Student; import com.demo.mapper.StudentMapper; import org.junit.Test; import org.junit.runner.RunWith; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import javax.annotation.Resource; @RunWith(SpringRunner.class) @MapperScan("com.demo.mapper") @SpringBootTest public class MPTest { @Resource private StudentMapper studentMapper; @Test public void insertTest() { Student student = new Student(); student.setId(1212); student.setStuName("蒋罗2"); student.setStuNumber("134513"); student.setAge(26); Integer inset1 = studentMapper.insert(student); System.out.println(student.getId()); } @Test public void updateTest() { Student student = new Student(); student.setId(1212); student.setStuName("蒋罗2222"); Integer update1 = studentMapper.updateById(student); System.out.println(update1); } @Test public void selectTest() { Student student = studentMapper.selectById(1001); System.out.println(student.getStuName()); } @Test public void deleteTest() { Integer delete1 = studentMapper.deleteById(1212); System.out.println(delete1); } @Test public void testWrapper() { /* EntityWrapper<Student> qureyWrapper = new EntityWrapper<>(); qureyWrapper.eq("id", "1001"); System.out.println(qureyWrapper);*/ QueryWrapper<Student> queryWrapper = new QueryWrapper<>(); queryWrapper.eq("id", "1002"); System.out.println(queryWrapper.getSqlSegment()); } }
The END!