Mybatis-Plus(简称MP)是一个 Mybatis 的增强工具,在 Mybatis 的基础上只做增强不做改变,为简化开发、提高效率而生。
中文文档 :http://baomidou.oschina.io/mybatis-plus-doc/#/
本文介绍包括
1)如何搭建
2)代码生成(controller、service、mapper、xml)
3)单表的CRUD、条件查询、分页 基类已经为你做好了
一、如何搭建
1. 首先我们创建一个 springboot 工程 --> https://start.spring.io/
2. maven 依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>2.3</version>
</dependency>
<!-- velocity 依赖,用于代码生成 -->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.0</version>
</dependency>
3. 配置(因为感觉太啰嗦,这里省略了数据源的配置)
application.properties
mybatis-plus.mapper-locations=classpath:/mapper/*Mapper.xml
mybatis-plus.typeAliasesPackage=com.taven.web.springbootmp.entity
mybatis-plus.global-config.id-type=3
mybatis-plus.global-config.field-strategy=2
mybatis-plus.global-config.db-column-underline=true
mybatis-plus.global-config.key-generator=com.baomidou.mybatisplus.incrementer.OracleKeyGenerator
mybatis-plus.global-config.logic-delete-value=1
mybatis-plus.global-config.logic-not-delete-value=0
mybatis-plus.global-config.sql-injector=com.baomidou.mybatisplus.mapper.LogicSqlInjector
#这里需要改成你的类
mybatis-plus.global-config.meta-object-handler=com.taven.web.springbootmp.MyMetaObjectHandler
mybatis-plus.configuration.map-underscore-to-camel-case=true
mybatis-plus.configuration.cache-enabled=false
mybatis-plus.configuration.jdbc-type-for-null=null
配置类 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执行效率插件【生产环境可以关闭】
*/
@Bean
public PerformanceInterceptor performanceInterceptor() {
return new PerformanceInterceptor();
}
/*
* 分页插件,自动识别数据库类型 多租户,请参考官网【插件扩展】
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
@Bean
public MetaObjectHandler metaObjectHandler() {
return new MyMetaObjectHandler();
}
/**
* 注入主键生成器
*/
@Bean
public IKeyGenerator keyGenerator() {
return new H2KeyGenerator();
}
/**
* 注入sql注入器
*/
@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;
/**
* 注入公共字段自动填充,任选注入方式即可
*/
//@Component
public class MyMetaObjectHandler extends MetaObjectHandler {
protected final static Logger logger = LoggerFactory.getLogger(Application.class);
@Override
public void insertFill(MetaObject metaObject) {
logger.info("新增的时候干点不可描述的事情");
}
@Override
public void updateFill(MetaObject metaObject) {
logger.info("更新的时候干点不可描述的事情");
}
}
二、代码生成
执行 junit 即可生成controller、service接口及实现、mapper及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>
* 测试生成代码
* </p>
*
* @author K神
* @date 2017/12/18
*/
public class GeneratorServiceEntity {
@Test
public void generateCode() {
String packageName = "com.taven.web.springbootmp";
boolean serviceNameStartWithI = false;//user -> UserService, 设置成true: user -> IUserService
generateByTables(serviceNameStartWithI, packageName, "cable", "station");//修改为你的表名
}
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);//修改替换成你需要的表名,多个表名传数组
config.setActiveRecord(false)
.setEnableCache(false)
.setAuthor("殷天文")
.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, tableNames);
// }
}
到这一步搭建已经基本完成了,下面就可以开始使用了!
三、使用 Mybatis-Plus
首先我们执行 上面的 generateCode()
会为我们基于 表结构 生成以下代码(xml是我手动移到下面的),service 和 mapper 已经继承了基类,为我们封装了很多方法,下面看几个简单的例子。
/**
* <p>
* 前端控制器
* </p>
*
* @author 殷天文
* @since 2018-05-31
*/
@Controller
@RequestMapping("/cable")
public class CableController {
@Autowired private CableService cableService;
/**
* list 查询测试
*
*/
@RequestMapping("/1")
@ResponseBody
public Object test1() {
// 构造实体对应的 EntityWrapper 对象,进行过滤查询
EntityWrapper<Cable> ew = new EntityWrapper<>();
ew.where("type={0}", 1)
.like("name", "王")
.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";
}
/**
* 分页 查询测试
*/
@RequestMapping("/2")
@ResponseBody
public Object test2() {
// 构造实体对应的 EntityWrapper 对象,进行过滤查询
EntityWrapper<Cable> ew = new EntityWrapper<>();
ew.where("type={0}", 1)
// .like("name", "王")
.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;
}
/**
* 自定义查询字段
*/
@RequestMapping("/3")
@ResponseBody
public Object test3() {
Object vl = null;
// 构造实体对应的 EntityWrapper 对象,进行过滤查询
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", "王")
.where(false, "voltage_level=#{0}", vl);//当vl 为空时,不拼接
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("测试光缆");
cableService.insert(c);
return "ok";
}
/**
* update
*/
@RequestMapping("/5")
@ResponseBody
public Object test5() {
Cable c = cableService.selectById(22284l);
c.setName("测试光缆2222");
c.setType(1);
cableService.updateById(c);
return "ok";
}
}
网友评论