SpringCloud如何集成Mybatis-Plus做基础的Crud?
Mybatis-plus简介:
:Mybatis-plus是对Mybatis框架的二次封装和扩展纯正血统
:完全继承原生 Mybatis 的所有特性最少依赖
:仅仅依赖Mybatis以及Mybatis-Spring性能损耗小
:启动即会自动注入基本CURD ,性能无损耗,直接面向对象操作自动热加载
:Mapper对应的xml可以热加载,大大减少重启Web服务器时间,提升开发效率
:自带Sql性能分析插件,开发测试时,能有效解决慢查询全局拦截
:提供全表delete、update操作智能分析阻断避免Sql注入
:内置Sql注入内容剥离器,预防Sql注入攻击
步骤一:
新建基础代码模块,在src目录下放入生成代码的主类GenteratorCode:
package com.baidu.yh;
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.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DbType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import java.util.*;
/**
* 生成代码的主类
*/
public class GenteratorCode {
public static void main(String[] args) throws InterruptedException {
//用来获取Mybatis-Plus.properties文件的配置信息
ResourceBundle rb = ResourceBundle.getBundle("mybatiesplus-config-article"); //不要加后缀不要加后缀不要加后缀不要加后缀不要加后缀
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
gc.setOutputDir(rb.getString("OutputDir"));
gc.setFileOverride(false);
gc.setActiveRecord(true);// 开启 activeRecord 模式
gc.setEnableCache(false);// XML 二级缓存
gc.setBaseResultMap(true);// XML ResultMap
gc.setBaseColumnList(false);// XML columList
gc.setAuthor(rb.getString("author"));
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setDbType(DbType.MYSQL);
dsc.setTypeConvert(new MySqlTypeConvert());
dsc.setDriverName(rb.getString("jdbc.driver"));
dsc.setUsername(rb.getString("jdbc.user"));
dsc.setPassword(rb.getString("jdbc.pwd"));
dsc.setUrl(rb.getString("jdbc.url"));
mpg.setDataSource(dsc);
// 表策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setTablePrefix(new String[] { "tb_" });// 此处可以修改为您的表前缀
strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略
strategy.setInclude(new String[]{
"tb_article",
"tb_channel",
"tb_column"
}); // 需要生成的表
mpg.setStrategy(strategy);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setParent(rb.getString("parent")); //com.baidu.yh
pc.setController("web.controller"); //com.baidu.yh.web.controller
pc.setService("service");
pc.setServiceImpl("service.impl");
pc.setEntity("domain");
pc.setMapper("mapper");
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() + "-rb");
this.setMap(map);
}
};
List<FileOutConfig> focList = new ArrayList<FileOutConfig>();
//controller的输出配置
focList.add(new FileOutConfig("/templates/controller.java.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
//合并好的内容输出到哪儿?
return rb.getString("OutputDir")+ "/com/baidu/yh/web/controller/" + tableInfo.getEntityName() + "Controller.java";
}
});
//query的输出配置
focList.add(new FileOutConfig("/templates/query.java.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
return rb.getString("OutputDirBase")+ "/com/baidu/yh/query/" + tableInfo.getEntityName() + "Query.java";
}
});
// 调整 domain 生成目录演示
focList.add(new FileOutConfig("/templates/entity.java.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
return rb.getString("OutputDirBase")+ "/com/baidu/yh/domain/" + tableInfo.getEntityName() + ".java";
}
});
// 调整 xml 生成目录演示
focList.add(new FileOutConfig("/templates/mapper.xml.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
return rb.getString("OutputDirXml")+ "/com/baidu/yh/mapper/" + tableInfo.getEntityName() + "Mapper.xml";
}
});
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
// 自定义模板配置,可以 copy 源码 mybatis-plus/src/main/resources/templates 下面内容修改,
// 放置自己项目的 src/main/resources/templates 目录下, 默认名称一下可以不配置,也可以自定义模板名称
TemplateConfig tc = new TemplateConfig();
tc.setService("/templates/service.java.vm");
tc.setServiceImpl("/templates/serviceImpl.java.vm");
tc.setMapper("/templates/mapper.java.vm");
tc.setEntity(null);
tc.setController(null);
tc.setXml(null);
// 如上任何一个模块如果设置 空 OR Null 将不生成该模块。
mpg.setTemplate(tc);
// 执行生成
mpg.execute();
}
}
步骤二:
在resources资源文件夹里面templates模板文件夹,templates里面有controller.java.vm和query.java.vm;
controller.java.vm:
package ${package.Controller};
import ${package.Service}.${table.serviceName};
import ${package.Entity}.${entity};
import com.baidu.yh.query.${entity}Query;
import com.baidu.yh.util.AjaxResult;
import com.baidu.yh.util.PageList;
import com.baomidou.mybatisplus.plugins.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/${table.entityPath}")
public class ${entity}Controller {
@Autowired
public ${table.serviceName} ${table.entityPath}Service;
/**
* 保存和修改公用的
* @param ${table.entityPath} 传递的实体
* @return Ajaxresult转换结果
*/
@RequestMapping(value="/save",method= RequestMethod.POST)
public AjaxResult save(@RequestBody ${entity} ${table.entityPath}){
try {
if(${table.entityPath}.getId()!=null){
${table.entityPath}Service.updateById(${table.entityPath});
}else{
${table.entityPath}Service.insert(${table.entityPath});
}
return AjaxResult.me();
} catch (Exception e) {
e.printStackTrace();
return AjaxResult.me().setSuccess(false).setMessage("保存对象失败!"+e.getMessage());
}
}
/**
* 删除对象信息
* @param id
* @return
*/
@RequestMapping(value="/{id}",method=RequestMethod.DELETE)
public AjaxResult delete(@PathVariable("id") Long id){
try {
${table.entityPath}Service.deleteById(id);
return AjaxResult.me();
} catch (Exception e) {
e.printStackTrace();
return AjaxResult.me().setSuccess(false).setMessage("删除对象失败!"+e.getMessage());
}
}
//获取用户
@RequestMapping(value = "/{id}",method = RequestMethod.GET)
public ${entity} get(@PathVariable("id")Long id)
{
return ${table.entityPath}Service.selectById(id);
}
/**
* 查看所有的员工信息
* @return
*/
@RequestMapping(value = "/list",method = RequestMethod.GET)
public List<${entity}> list(){
return ${table.entityPath}Service.selectList(null);
}
/**
* 分页查询数据
*
* @param query 查询对象
* @return PageList 分页对象
*/
@RequestMapping(value = "/pagelist",method = RequestMethod.POST)
public PageList<${entity}> json(@RequestBody ${entity}Query query)
{
Page<${entity}> page = new Page<${entity}>(query.getPage(),query.getRows());
page = ${table.entityPath}Service.selectPage(page);
return new PageList<${entity}>(page.getTotal(),page.getRecords());
}
}
query.java.vm:
package com.baidu.yh.query;
/**
*
* @author ${author}
* @since ${date}
*/
public class ${table.entityName}Query extends BaseQuery{
}
步骤三:
放入配置文件比如:mybatiesplus-config-article.properties
#代码输出基本路径
OutputDir=E:/work/my_idea_project/tensquare_parent/tensquare_article/src/main/java
#mapper.xml SQL映射文件目录
OutputDirXml=E:/work/my_idea_project/tensquare_parent/tensquare_article/src/main/resources
#domain的输出路径
OutputDirBase=E:/work/my_idea_project/tensquare_parent/tensquare_article/src/main/java
#设置作者
author=Mr.Yang
#自定义包路径:基础包的路径
parent=com.baidu.yh
#数据库连接信息
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://192.168.200.128:3306/tensquare_article?characterEncoding=utf-8
jdbc.user=root
jdbc.pwd=root
步骤四:
在pom.xml里面导入相应的依赖包:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>tensquare_parent</artifactId>
<groupId>com.tensquare</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>tensquare_generate_code</artifactId>
<dependencies>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
<!--模板引擎-->
<dependency>
<groupId>org.apache.velocity</groupId>
<artifactId>velocity-engine-core</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
</project>
步骤五:
1.新建资源微服务,pom.xml导入依赖包:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>tensquare_parent</artifactId>
<groupId>com.tensquare</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>tensquare_article</artifactId>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.tensquare</groupId>
<artifactId>tensquare_common</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!--连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.9</version>
</dependency>
</dependencies>
</project>
2.配置文件配置:application.yml
server:
port: 9004 #服务访问端口号
spring:
application:
name: tensquare_article #服务名称
datasource: #数据库连接的四大属性
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://192.168.200.128:3306/tensquare_article?characterEncoding=utf-8
username: root
password: root
type: com.alibaba.druid.pool.DruidDataSource
mybatis-plus: #配置mybatis-plus
mapper-locations: classpath:com/baidu/yh/mapper/*Mapper.xml #sql映射文件地址
#config-location: classpath:mybatis.xml #mybatis的配置文件
#type-aliases-package: cn.itsource.hrm.domain,cn.itsource.hrm.query
3.启动类:ArticleApplication:
package com.baidu.yh;
import com.baidu.yh.util.IdWorker;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
@MapperScan("com.baidu.yh.mapper")
public class ArticleApplication {
public static void main(String args[]) {
SpringApplication.run(ArticleApplication.class,args);
}
@Bean
public IdWorker createIdWorker() {
return new IdWorker(1, 1);
}
}