1.创建项目并导入相关maven依赖
com.baomidou mybatis-plus-boot-starter2.2.0 org.apache.velocity velocity-engine-core2.0 mysql mysql-connector-java
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() { Mapmap = new HashMap (); map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-rb"); this.setMap(map); } }; List focList = new ArrayList (); // 调整 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; @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()); } } @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); } @GetMapping() public List<${entity}> list(){ return ${table.entityPath}Service.selectList(null); } @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
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 { @RequestMapping(value="/add",method= RequestMethod.POST) AjaxResult save(${entity} ${table.entityPath}); @RequestMapping(value="/delete/{id}",method=RequestMethod.DELETE) AjaxResult delete(@PathVariable("id") Integer id); //获取用户 @RequestMapping("/{id}") ${entity} get(@RequestParam(value="id",required=true) Long id); @RequestMapping("/list") public List<${entity}> list(); @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; } }; } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)