欢迎您访问365答案网,请分享给你的朋友!
生活常识 学习资料

java代码生成项目

时间:2023-08-04

1.创建项目并导入相关maven依赖

com.baomidou mybatis-plus-boot-starter 2.2.0 org.apache.velocity velocity-engine-core 2.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\resourcesOutputDirbase=F:\ideaworkspace\mybatisplus\src\main\java#设置作者author=chunwai#自定义包路径parent=com.chunwai.mybatisplus.mybatisplus#数据库连接信息jdbc.driver=com.mysql.cj.jdbc.Driverjdbc.url=jdbc:mysql:///testjdbc.user=rootjdbc.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 map = 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@Configurationpublic 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;@Componentpublic 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; } }; }}

Copyright © 2016-2020 www.365daan.com All Rights Reserved. 365答案网 版权所有 备案号:

部分内容来自互联网,版权归原作者所有,如有冒犯请联系我们,我们将在三个工作时内妥善处理。