1.创建项目并导入相关maven依赖
<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>
2.yml相关配置
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/test
username: root
password: root
3.配置相关所需properties文件(添加到resource目录下resource/mybatiesplus.properties)
#此处为本项目src所在路径(代码生成器输出路径),注意一定是当前项目所在的目录哟
OutputDir=F:\\ideaworkspace\\mybatisplus\\src\\main\\java
#mapper.xml SQL映射文件目录
OutputDirXml=F:\\ideaworkspace\\mybatisplus\\src\\main\\resources
OutputDirBase=F:\\ideaworkspace\\mybatisplus\\src\\main\\java
#设置作者
author=chunwai
#自定义包路径
parent=com.chunwai.mybatisplus.mybatisplus
#数据库连接信息
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql:///test
jdbc.user=root
jdbc.pwd=root
4.生成代码主方法
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 {
//用来获取Mybatisplus.properties文件的配置信息
ResourceBundle rb = ResourceBundle.getBundle("mybatitsplus"); //不要加后缀
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
gc.setOutputDir(rb.getString("OutputDir"));
gc.setFileOverride(true);
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[] { "t_" });// 此处可以修改为您的表前缀
strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略
strategy.setInclude(new String[]{"t_user"}); // 需要生成的表
mpg.setStrategy(strategy);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setParent(rb.getString("parent"));
pc.setController("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>();
// 调整 domain 生成目录演示
focList.add(new FileOutConfig("/templates/entity.java.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
return rb.getString("OutputDirBase")+ "/com/chunwai/mybatisplus/domain/" + tableInfo.getEntityName() + ".java";
}
});
//query
focList.add(new FileOutConfig("/templates/query.java.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
return rb.getString("OutputDirBase")+ "/com/chunwai/mybatisplus/query/" + tableInfo.getEntityName() + "Query.java";
}
});
// 调整 xml 生成目录演示
focList.add(new FileOutConfig("/templates/mapper.xml.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
return rb.getString("OutputDirXml")+ "/com/chunwai/mybatisplus/mapper/" + tableInfo.getEntityName() + "Mapper.xml";
}
});
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
// 自定义模板配置,可以将我提供的相关源码放到resources/templates下面内容修改,
// 放置自己项目的 src/main/resources/templates 目录下, 默认名称一下可以不配置,也可以自定义模板名称
TemplateConfig tc = new TemplateConfig();
tc.setService("/templates/service.java.vm");
tc.setServiceImpl("/templates/serviceImpl.java.vm");
tc.setEntity(null);
tc.setMapper("/templates/mapper.java.vm");
//tc.setController(null);
tc.setXml(null);
// 如上任何一个模块如果设置 空 OR Null 将不生成该模块。
mpg.setTemplate(tc);
// 执行生成
mpg.execute();
}
}
5.mybatisplus分页插件配置
import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
//Spring boot方式
@EnableTransactionManagement
@Configuration
public class MybatisPlusConfig {
/**
* 分页插件
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
}
?
以下为自定义模板配置相关源码
?自定义controller模板,文件名为:controller.java.vm
package ${package.Controller};
import ${package.Service}.${table.serviceName};
import ${package.Entity}.${entity};
import cn.itsource.hrm.query.${entity}Query;
import cn.itsource.hrm.util.AjaxResult;
import cn.itsource.hrm.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转换结果
*/
@PutMapping
public AjaxResult addOrUpdate(@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().setMessage("保存对象失败!"+e.getMessage());
}
}
/**
* 删除对象信息
* @param id
* @return
*/
@DeleteMapping(value="/{id}")
public AjaxResult delete(@PathVariable("id") Long id){
try {
${table.entityPath}Service.deleteById(id);
return AjaxResult.me();
} catch (Exception e) {
e.printStackTrace();
return AjaxResult.me().setMessage("删除对象失败!"+e.getMessage());
}
}
//获取用户
@GetMapping("/{id}")
public ${entity} get(@PathVariable("id")Long id){
return ${table.entityPath}Service.selectById(id);
}
/**
* 查看所有
* @return
*/
@GetMapping()
public List<${entity}> list(){
return ${table.entityPath}Service.selectList(null);
}
/**
* 分页查询数据
* @param query 查询对象
* @return PageList 分页对象
*/
@PostMapping("/list")
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模板,文件名为:query.java.vm
/**
* @author ${author}
* @since ${date}
*/
public class ${table.entityName}Query extends BaseQuery{
}
?自定义client模板,文件名为:client.java.vm
import ${package.Entity}.${entity};
import cn.itsource.hrm.query.${entity}Query;
import cn.itsource.hrm.util.AjaxResult;
import cn.itsource.hrm.util.PageList;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.cloud.openfeign.FeignClientsConfiguration;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@FeignClient(value = "ZUUL-GATEWAY",configuration = FeignClientsConfiguration.class,
fallbackFactory = ${entity}ClientHystrixFallbackFactory.class)
@RequestMapping("/product/${table.entityPath}")
public interface ${entity}Client {
/**
* 保存和修改公用的
* @param ${table.entityPath} 传递的实体
* @return Ajaxresult转换结果
*/
@RequestMapping(value="/add",method= RequestMethod.POST)
AjaxResult save(${entity} ${table.entityPath});
/**
* 删除对象信息
* @param id
* @return
*/
@RequestMapping(value="/delete/{id}",method=RequestMethod.DELETE)
AjaxResult delete(@PathVariable("id") Integer id);
//获取用户
@RequestMapping("/{id}")
${entity} get(@RequestParam(value="id",required=true) Long id);
/**
* 查看所有
* @return
*/
@RequestMapping("/list")
public List<${entity}> list();
/**
* 分页查询数据
*
* @param query 查询对象
* @return PageList 分页对象
*/
@RequestMapping(value = "/json",method = RequestMethod.POST)
PageList<${entity}> json(@RequestBody ${entity}Query query);
}
?自定义ClientHystrixFallbackFactory模板,文件名为:ClientHystrixFallbackFactory.java.vm
import ${package.Entity}.${entity};
import cn.itsource.hrm.query.${entity}Query;
import cn.itsource.hrm.util.AjaxResult;
import cn.itsource.hrm.util.PageList;
import feign.hystrix.FallbackFactory;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
public class ${entity}ClientHystrixFallbackFactory implements FallbackFactory<${entity}Client> {
@Override
public ${entity}Client create(Throwable throwable) {
return new ${entity}Client() {
@Override
public AjaxResult save(${entity} ${table.entityPath}) {
return null;
}
@Override
public AjaxResult delete(Integer id) {
return null;
}
@Override
public ${entity} get(Long id) {
return null;
}
@Override
public List<${entity}> list() {
return null;
}
@Override
public PageList<${entity}> json(${entity}Query query) {
return null;
}
};
}
}
|