Mybatis-Plus是一个优秀的Mybatis增强工具,目前更新到3.1.1。Mybatis-Plus原生提供了很多单表操作的方法,极大简化了繁琐的curd的操作,同时又支持xml配置、自定义sql的编写。这篇文章介绍SpringBoot2集成Mybatis-Plus 3.1.0,同时介绍mybatis提供MysqlGenerator.java,你可以通过指定的数据库表生成对应的bean、mapper.xml、mapper.java、service.java、serviceImpl.java,甚至controller
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druid-spring-boot-starterartifactId>
<version>1.1.10version>
dependency>
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plus-boot-starterartifactId>
<version>3.1.0version>
dependency>
<dependency>
<groupId>com.baomidougroupId>
<artifactId>mybatis-plus-generatorartifactId>
<version>3.1.0version>
dependency>
<dependency>
<groupId>org.freemarkergroupId>
<artifactId>freemarkerartifactId>
dependency>
mybatis-plus:
global-config:
db-config:
id-type: auto
field-strategy: not_empty
table-underline: true
db-type: mysql
logic-delete-value: 1 # 逻辑已删除值(默认为 1)
logic-not-delete-value: 0 # 逻辑未删除值(默认为 0)
mapper-locations: classpath:/mapper/*.xml
当然,数据源也要配置,这里使用了上篇文章中demo-druid项目的配置,
spring:
datasource:
# 配置数据源
driver-class-name: com.mysql.jdbc.Driver
# 使用druid连接池
type: com.alibaba.druid.pool.DruidDataSource
url: jdbc:mysql://127.0.0.1:3306/demo_druid?characterEncoding=utf-8&autoReconnect=true&failOverReadOnly=false&useSSL=true
username: root
password: root
@Configuration
public class MyBatisPlusConfig {
private final static Logger logger = LoggerFactory.getLogger(MyBatisPlusConfig.class);
/**
* @description: 配置分页插件
*
* @author: gradual
* @date: 2019/1/15 10:17
* @param: []
* @return: com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
logger.debug("注册分页插件");
return new PaginationInterceptor();
}
/**
* @description: SQL执行效率插件
*
* @author: gradual
* @date: 19-1-24 下午4:59
* @param: []
* @return: com.baomidou.mybatisplus.extension.plugins.PerformanceInterceptor
*/
@Bean
@Profile({"test"})// 设置 dev test 环境开启
public PerformanceInterceptor performanceInterceptor() {
return new PerformanceInterceptor();
}
/**
* 逻辑删除用,3.1.1之后的版本可不需要配置该bean,但项目这里用的是3.1.0的
*
* @author David Hong
*
* @return com.baomidou.mybatisplus.core.injector.ISqlInjector
*/
@Bean
public ISqlInjector sqlInjector() {
return new LogicSqlInjector();
}
}
@SpringBootApplication
@MapperScan("com.yuan.demodruid.mapper")
public class DemoDruidApplication {
public static void main(String[] args) {
SpringApplication.run(DemoDruidApplication.class, args);
}
}
MysqlGenerator.java内容如下:
public class MysqlGenerator {
/**
* RUN THIS
*/
public static void main(String[] args) {
// 代码生成器
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath + "/src/main/java");
// TODO 设置用户名
gc.setAuthor("yuan");
gc.setOpen(true);
// service 命名方式
gc.setServiceName("%sService");
// service impl 命名方式
gc.setServiceImplName("%sServiceImpl");
// 自定义文件命名,注意 %s 会自动填充表实体属性!
gc.setMapperName("%sMapper");
gc.setXmlName("%sMapper");
gc.setFileOverride(true);
gc.setActiveRecord(true);
// XML 二级缓存
gc.setEnableCache(false);
// XML ResultMap
gc.setBaseResultMap(true);
// XML columList
gc.setBaseColumnList(false);
mpg.setGlobalConfig(gc);
// TODO 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://127.0.0.1:3306/demo_druid?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=UTC");
dsc.setDriverName("com.mysql.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("root");
mpg.setDataSource(dsc);
// TODO 包配置
PackageConfig pc = new PackageConfig();
//pc.setModuleName(scanner("模块名"));
pc.setParent("com.yuan.demodruid");
pc.setEntity("domain.entity");
pc.setService("service");
pc.setServiceImpl("service.impl");
mpg.setPackageInfo(pc);
// 自定义需要填充的字段
List<TableFill> tableFillList = new ArrayList<>();
//如 每张表都有一个创建时间、修改时间
//而且这基本上就是通用的了,新增时,创建时间和修改时间同时修改
//修改时,修改时间会修改,
//虽然像Mysql数据库有自动更新几只,但像ORACLE的数据库就没有了,
//使用公共字段填充功能,就可以实现,自动按场景更新了。
//如下是配置
//TableFill createField = new TableFill("gmt_create", FieldFill.INSERT);
//TableFill modifiedField = new TableFill("gmt_modified", FieldFill.INSERT_UPDATE);
//tableFillList.add(createField);
//tableFillList.add(modifiedField);
// 自定义配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
List<FileOutConfig> focList = new ArrayList<>();
focList.add(new FileOutConfig("/templates/mapper.xml.ftl") {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输入文件名称
return projectPath + "/src/main/resources/mapper/"
+ "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_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);
// 设置逻辑删除键
strategy.setLogicDeleteFieldName("deleted");
// TODO 指定生成的bean的数据库表名
strategy.setInclude("mp_user");
//strategy.setSuperEntityColumns("id");
// 驼峰转连字符
strategy.setControllerMappingHyphenStyle(true);
mpg.setStrategy(strategy);
// 选择 freemarker 引擎需要指定如下加,注意 pom 依赖必须有!
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
}
如果你要使用上面代码,留意修改上面TODO部分即可,修改后,run main()方法,文件会生成在指定目录,比如下面的数据库表
create table if not exists demo_druid.mp_user
(
id bigint unsigned auto_increment
primary key,
username varchar(32) null,
address varchar(64) null,
openid varchar(32) null,
gmt_create timestamp default CURRENT_TIMESTAMP null,
gmt_modified timestamp default CURRENT_TIMESTAMP null on update CURRENT_TIMESTAMP,
deleted tinyint unsigned default 0 null
);
生成的bean如下:
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class MpUser extends Model<MpUser> {
private static final long serialVersionUID = 1L;
@TableId(value = "id", type = IdType.AUTO)
private Long id;
private String username;
private String address;
private String openid;
private LocalDateTime gmtCreate;
private LocalDateTime gmtModified;
@TableLogic
private Integer deleted;
@Override
protected Serializable pkVal() {
return this.id;
}
}
生成的mapper.java和service和serviceImpl分别如下
@Repository
public interface MpUserMapper extends BaseMapper<MpUser> {
}
public interface MpUserService extends IService<MpUser> {
}
@Service
public class MpUserServiceImpl extends ServiceImpl<MpUserMapper, MpUser> implements MpUserService {
}
上面MysqlGenerator帮我们生成了bean.java、mapper.xml、mapper.java、Iservice.java、serviceImpl.java。操作单表时,注入serviceImpl对象即可使用。简单示例如下:
@Autowired
private MpUserService mpUserService;
@Test
public void test1() {
// 插入新记录
MpUser mpUser = new MpUser();
mpUser.setId(1L);
mpUser.setOpenid("openId");
mpUser.setAddress("广东深圳");
mpUser.setUsername("David Hong");
mpUserService.save(mpUser);
// 或者
mpUser.insertOrUpdate();
// 更新完成后,mpUser对象的id会被补全
log.info("mpUser={}", mpUser.toString());
// 通过主键id查询
mpUser = mpUserService.getById(8);
log.info("mpUser={}", mpUser.toString());
// 条件查询,下面相当于xml中的 select * from mp_user where address = '"广东深圳' and username = 'David Hong' limit 1
mpUser = mpUserService.getOne(new QueryWrapper<MpUser>().eq("address", "广东深圳").eq("username", "David Hong").last("limit 1"));
// 批量查询
List<MpUser> mpUserList = mpUserService.list();
// 分页查询
int pageNum = 1;
int pageSize = 10;
IPage<MpUser> mpUserIPage = mpUserService.page(new Page<>(pageNum, pageSize), new QueryWrapper<MpUser>().eq("openid", "openId"));
// IPage to List
List<MpUser> mpUserList1 = mpUserIPage.getRecords();
// 总页数
long allPageNum = mpUserIPage.getPages();
// 修改更新
mpUser.setAddress("广东广州");
mpUserService.updateById(mpUser);
// 或者
mpUser.insertOrUpdate();
// 通过主键id删除
mpUserService.removeById(1);
// 或者
mpUser.deleteById();
}
更多内容,请参考官方示例
面对多表联合查询的需求,可在对应mapper.xml中编写sql
GitHub