idea项目 --- 2.数据库的使用

1.在resources先新建mybatis-generator.xml资源文件

<?xml version="1.0" encoding="UTF-8"?>    
<!DOCTYPE generatorConfiguration
    PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
    "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<!--这个是你springboot的配置文件,它会加载spring的配置-->
<!--     <properties resource="application.yml"/> -->

<!-- 必须要有这个 mysql驱动的位置 这个是MySQL连接的jar包,你需要指定你自己计算机上的jar包的位置,我用的自己本机的maven仓库的,注意别只复制这个jar存在的路径,在最后边要加上jar的名字哦。细节细节-->
<classPathEntry location="C:\Users\zhilong.zhang\.m2\repository\mysql\mysql-connector-java\8.0.16\mysql-connector-java-8.0.16.jar"/>
<context id="Tables" targetRuntime="MyBatis3">

    <!-- 生成 JavaBean 对象重写 toString方法 -->
    <plugin type="org.mybatis.generator.plugins.ToStringPlugin"/>
     <!-- 取消生成注释 -->
    <commentGenerator>
        <property name="suppressAllComments" value="true"/>
    </commentGenerator>

    <!--这是mysql连接的配置信息,DriverClass的路径是否存在 cj 看自己mysql连接的版本   5.xx没有cj。6.xx的有cj-->
    <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                    connectionURL="jdbc:mysql://localhost:3306/test?serverTimezone=GMT"
                    userId="root"
                    password="password">
        <!--这个很重要,没有的话,会发生一些奇怪的问题,稍后细讲!-->
        <property name="nullCatalogMeansCurrent" value="true" />

    </jdbcConnection>

    <!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 和NUMERIC 类型解析为java.math.BigDecimal  涉及金额就要注意了哟-->
    <javaTypeResolver>
        <property name="forceBigDecimals" value="false" />
    </javaTypeResolver>

    <!--指定javaBean生成的位置 targetProject="./src/main/java" 注意src前面有个zf-->
    <!--targetPackage="com.chenggongyuan.xunjian.pojo",这里是自己项目的名字,下面的都得替换成自己的项目名称-->
    <javaModelGenerator targetPackage="com.test.demoApp.Domain"
                        targetProject="demoApp/src/main/java">
        <!--这个为true 逆向工程可能会生成子包-->
        <property name="enableSubPackages" value="true"/>
        <property name="trimStrings" value="true"/>
    </javaModelGenerator>

    <!-- 指定sql映射文件生成位置 -->
    <sqlMapGenerator targetPackage="Mapper" targetProject="demoApp/src/main/resources">
        <property name="enableSubPackages" value="false"/>
    </sqlMapGenerator>

    <!-- 指定dao接口生成的位置,mapper接口 -->
    <javaClientGenerator type="XMLMAPPER" targetPackage="com.test.demoApp.Dao"
                         targetProject="demoApp/src/main/java">
        <property name="enableSubPackages" value="true"/>
    </javaClientGenerator>

    <!-- 制定每个表的生成策略 这里可以写多个表,表名和需要生成的pojo名写正确 -->
    <table tableName="post" domainObjectName="post"></table>
</context>
</generatorConfiguration>

2.数据库数据的生成,我使用的word的可视化数据生成yml文件简单、方便,你可以去我的百度提取
链接:https://pan.baidu.com/s/1iNaEubwrQk9UvUO2aD3UOw
提取码:LONG
--- 你可以 ( 数据表_tool生成用.xlsm ) 这个文档就是数据库数据表的新建,非常方便观看和使用,然后用 ( genfile.xlsm) 生成 ( fieldDef.yml ) ,可以将yml放在resources的资源文件夹
3.将fieldDef.yml的文件生成数据库的数据表,先install在html调用生成接口all

@RestController
@RequestMapping(value = "gen")
public class GenToolsController {

@Autowired
DomainGenerator domainGenerator;

@Autowired
RepoGenerator repoGeregenerator;

@Autowired
CtrlGenerator ctrlGenerator;

@GetMapping("/all")
public String all() throws Exception {
    domainGenerator.execute();
    repoGeregenerator.execute();
    ctrlGenerator.execute();
    return "OK";
}

@GetMapping("/domain")
public String domain() throws Exception {
    domainGenerator.execute();
    return "OK";
}

@GetMapping("/repo")
public String repo() throws Exception {
    repoGeregenerator.execute();
    return "OK";
}

@GetMapping("/ctrl")
public String ctrl() throws Exception {
    ctrlGenerator.execute();
    return "OK";
}
}

调用all接口就可以在数据库生成数据表
同时还有几个

  @Component
public class CtrlGenerator {
private GenProperties genProperties;

@Autowired
public CtrlGenerator(GenProperties genProperties) {
    this.genProperties = genProperties;
}

public void execute() throws Exception {
    String projectDir = this.getClass().getResource("/").getPath().replace("target/classes/", "");
    File distDir = new File(projectDir, "src/main/java/com/test/demoApp/gen/controller");
    System.out.println(distDir);

    System.out.println("开始生成");

    String[] types = {"Long", "String"};
    List typeList = Arrays.asList(types);

    genProperties.getControllers().forEach(item -> {
        try {
            String domainName = item.getDomain();
            GenProperties.DomainConf domainConf = genProperties.findDomian(domainName);
            String repoName = item.getRepository();
            String ctrlName = item.getName();
            String tagsName = item.getTags();

            List<String> fileLineList = new ArrayList<>();
            fileLineList.add("package com.test.demoApp.gen.controller;");
            fileLineList.add("");
            fileLineList.add("import com.querydsl.core.types.dsl.BooleanExpression;");
            fileLineList.add("import com.querydsl.jpa.impl.JPAQueryFactory;");
            fileLineList.add("import com.test.demoApp.fixed.common.*;");
            fileLineList.add("import com.test.demoApp.gen.domain.*;");
            fileLineList.add("import com.test.demoApp.gen.repository.*;");
            fileLineList.add("import io.swagger.annotations.Api;");
            fileLineList.add("import io.swagger.annotations.ApiOperation;");
            fileLineList.add("import io.swagger.annotations.ApiParam;");
            fileLineList.add("import org.apache.commons.lang.StringUtils;");
            fileLineList.add("import org.springframework.beans.factory.annotation.Autowired;");
            fileLineList.add("import org.springframework.http.HttpStatus;");
            fileLineList.add("import org.springframework.transaction.annotation.Transactional;");
            fileLineList.add("import org.springframework.web.bind.annotation.*;");
            fileLineList.add("import java.sql.Timestamp;");
            fileLineList.add("import java.math.BigDecimal;");
            fileLineList.add("import java.util.*;");
            fileLineList.add("");
            fileLineList.add("@Api(value = \""+WordUtils.uncapitalize(domainName)+"\", tags = \"" +tagsName+ "\")");
            fileLineList.add("@RestController");
            fileLineList.add("@RequestMapping(value = \"/gen/"+ WordUtils.uncapitalize(domainName)+"\")");
            fileLineList.add("@SuppressWarnings(\"unchecked\")");
            fileLineList.add("public class "+ctrlName+" {");
            fileLineList.add("");
            fileLineList.add("    @Autowired");
            fileLineList.add("    "+repoName+" "+WordUtils.uncapitalize(repoName)+";");
            fileLineList.add("");
            fileLineList.add("    @Autowired");
            fileLineList.add("    JPAQueryFactory queryFactory;");
            fileLineList.add("");


            // 单条数据检索方法生成
            fileLineList.add("    @ApiOperation(value = \"查询单条\",");
            fileLineList.add("            notes = \"通过id检索\")");
            fileLineList.add("    @GetMapping(value = \"/queryOne\")");
            fileLineList.add("    @ResponseStatus(code = HttpStatus.OK)");
            fileLineList.add("    public ApiResult<"+domainName+"> query(");
            fileLineList.add("            @RequestParam(required = false) Long id) {");
            fileLineList.add("        "+domainName+" data = " + WordUtils.uncapitalize(repoName) + ".getOne(id);;");

            fileLineList.add("        return ApiResultBuilder.create().code(ApiResultCode.Success.code()).msg(ApiResultCode.Success.msg())");
            fileLineList.add("                .data(data).build();");
            fileLineList.add("    }");
            fileLineList.add("");

            // 分页检索方法生成
            fileLineList.add("    @ApiOperation(value = \"查询\",");
            fileLineList.add("            notes = \"支持分页查询,默认返回10条记录\")");
            fileLineList.add("    @GetMapping(value = \"/query\")");
            fileLineList.add("    @ResponseStatus(code = HttpStatus.OK)");
            fileLineList.add("    public ApiResult<List<"+domainName+">> query(");
            fileLineList.add("            @RequestParam(required = false) Long id,");

            List<String> domainFields = domainConf.getFields();
            domainFields.forEach(fieldDef ->{
                String[] fieldInfo = StringUtils.splitPreserveAllTokens(fieldDef, "|");
                String comment = fieldInfo[0];
                String fieldName = fieldInfo[1];
                String fieldType = fieldInfo[2];
                String relation = fieldInfo[3];
                String mainTableFlag = fieldInfo[4];

                if (StringUtils.isEmpty(relation)) {
                    fileLineList.add("            @RequestParam(required = false) @ApiParam(value = \""+comment+"\") "+fieldType+" "+fieldName+",");
                }

            });

            fileLineList.add("            @RequestParam(required = false) @ApiParam(value = \"页码\") Long page,");
            fileLineList.add("            @RequestParam(required = false) @ApiParam(value = \"限制条数\") Long limit) {");
            fileLineList.add("");
            fileLineList.add("        // 关联表");
            fileLineList.add("        Q"+domainName+" q"+domainName+" = Q"+domainName+"."+WordUtils.uncapitalize(domainName)+";");
            fileLineList.add("");
            fileLineList.add("        // 检索条件构造");
            fileLineList.add("        BooleanExpression whereExp = q"+domainName+".id.eq(q"+domainName+".id);");
            fileLineList.add("        if (id != null) {");
            fileLineList.add("            whereExp = whereExp.and(q"+domainName+".id.eq(id));");
            fileLineList.add("        }");

            domainFields.forEach(fieldDef ->{
                String[] fieldInfo = StringUtils.splitPreserveAllTokens(fieldDef, "|");
                String comment = fieldInfo[0];
                String fieldName = fieldInfo[1];
                String fieldType = fieldInfo[2];
                String relation = fieldInfo[3];
                String mainTableFlag = fieldInfo[4];

                if (StringUtils.isEmpty(relation)) {

                    if ("Long".equals(fieldType)
                            || "Timestamp".equals(fieldType)
                            || "BigDecimal".equals(fieldType)
                            || "Integer".equals(fieldType)
                            || "Double".equals(fieldType)
                            || "Float".equals(fieldType)
                            || "Short".equals(fieldType)
                            || "Byte".equals(fieldType)) {
                        fileLineList.add("        if ("+fieldName+" != null) {");
                        fileLineList.add("            whereExp = whereExp.and(q"+domainName+"."+fieldName+".eq("+fieldName+"));");
                        fileLineList.add("        }");
                    } else if ("String".equals(fieldType)) {
                        fileLineList.add("        if (StringUtils.isNotEmpty("+fieldName+")) {");
                        fileLineList.add("            whereExp = whereExp.and(q"+domainName+"."+fieldName+".eq("+fieldName+"));");
                        fileLineList.add("        }");
                    }
                }

            });

            fileLineList.add("");
            fileLineList.add("        // 件数取得");
            fileLineList.add("        Long count = queryFactory.selectFrom(q"+domainName+").where(whereExp).fetchCount();");
            fileLineList.add("        if (count == 0) {");
            fileLineList.add("            return ApiResultBuilder.create().code(ApiResultCode.Fail.code()).msg(\"没有检索到任何数据\").build();");
            fileLineList.add("        }");
            fileLineList.add("");
            fileLineList.add("        // 分页控制信息构造");
            fileLineList.add("        ApiPagination pagination = new ApiPagination(page, limit, count);");
            fileLineList.add("");
            fileLineList.add("        // 数据检索");
            fileLineList.add("        List<"+domainName+"> data = queryFactory");
            fileLineList.add("                    .selectFrom(q"+domainName+")");
            fileLineList.add("                    .where(whereExp)");
            fileLineList.add("                    .offset(pagination.getOffset())");
            fileLineList.add("                    .limit(pagination.getLimit())");
            fileLineList.add("                    .fetch();");
            fileLineList.add("");
            fileLineList.add("        // 分页数据返回");
            fileLineList.add("        return ApiResultBuilder.create().code(0).msg(\"成功返回\").data(data).pagination(pagination).build();");
            fileLineList.add("    }");
            fileLineList.add("");


            // 插入/更新方法生成
            fileLineList.add("    @ApiOperation(value = \"保存\")");
            fileLineList.add("    @PostMapping(value = \"/save\")");
            fileLineList.add("    @ResponseStatus(code = HttpStatus.OK)");
            fileLineList.add("    @Transactional");
            fileLineList.add("    public ApiResult<"+domainName+"> save(@RequestBody ApiParams<"+domainName+"> params) {");
            fileLineList.add("        "+domainName+" target = null;");
            //fileLineList.add("        Q"+domainName+" q"+domainName+" = Q"+domainName+"."+WordUtils.uncapitalize(domainName)+";");
            fileLineList.add("");
            fileLineList.add("        // 新建");
            fileLineList.add("        if (params.getData().getId() == null) {");
            fileLineList.add("            target = params.getData();");
            fileLineList.add("            target.setCreatedTime(new Timestamp(System.currentTimeMillis()));");
            fileLineList.add("            target.setLastUpdateTime(new Timestamp(System.currentTimeMillis()));");
            fileLineList.add("        // 更新");
            fileLineList.add("        } else {");
            fileLineList.add("            target = "+WordUtils.uncapitalize(repoName)+".getOne(params.getData().getId());");
            fileLineList.add("            if (params.getData().getVersion() != target.getVersion()) {");
            fileLineList.add("                return ApiResultBuilder.create().code(ApiResultCode.DataIllegality.code())");
            fileLineList.add("                        .msg(ApiResultCode.DataIllegality.msg()).build();");
            fileLineList.add("            }");
            domainFields.forEach(fieldDef ->{
                String[] fieldInfo = StringUtils.splitPreserveAllTokens(fieldDef, "|");
                String comment = fieldInfo[0];
                String fieldName = fieldInfo[1];
                String fieldType = fieldInfo[2];
                String relation = fieldInfo[3];
                String mainTableFlag = fieldInfo[4];

                if ("Long".equals(fieldType)
                        || "Timestamp".equals(fieldType)
                        || "BigDecimal".equals(fieldType)
                        || "Integer".equals(fieldType)
                        || "Double".equals(fieldType)
                        || "Float".equals(fieldType)
                        || "Short".equals(fieldType)
                        || "Byte".equals(fieldType)) {
                    fileLineList.add("            if (params.getData().get"+WordUtils.capitalize(fieldName)+"() != null) {");
                    fileLineList.add("                target.set"+WordUtils.capitalize(fieldName)+"(params.getData().get"+WordUtils.capitalize(fieldName)+"());");
                    fileLineList.add("            }");
                } else if ("String".equals(fieldType)) {
                    fileLineList.add("            if (StringUtils.isNotEmpty(params.getData().get"+WordUtils.capitalize(fieldName)+"())) {");
                    fileLineList.add("                target.set"+WordUtils.capitalize(fieldName)+"(params.getData().get"+WordUtils.capitalize(fieldName)+"());");
                    fileLineList.add("            }");
                }

            });
            fileLineList.add("            target.setLastUpdateTime(new Timestamp(System.currentTimeMillis()));");
            fileLineList.add("        }");
            fileLineList.add("        target = "+WordUtils.uncapitalize(repoName)+".save(target);");
            fileLineList.add("        return ApiResultBuilder.create().code(ApiResultCode.Success.code()).msg(ApiResultCode.Success.msg())");
            fileLineList.add("                .data(target).build();");
            fileLineList.add("    }");
            fileLineList.add("");

            // 删除方法
            fileLineList.add("    @ApiOperation(value = \"物理删除\")");
            fileLineList.add("    @PostMapping(value = \"/delete\")");
            fileLineList.add("    @ResponseStatus(code = HttpStatus.OK)");
            fileLineList.add("    @Transactional");
            fileLineList.add("    public ApiResult delete(@RequestBody ApiParams<List<String>> deleteParams) {");
            fileLineList.add("");
            fileLineList.add("        if (deleteParams.getData() == null) {");
            fileLineList.add("            return ApiResultBuilder.create()");
            fileLineList.add("                    .code(ApiResultCode.DataIllegality.code())");
            fileLineList.add("                    .msg(ApiResultCode.DataIllegality.msg()).build();");
            fileLineList.add("        }");
            fileLineList.add("");
            fileLineList.add("        for (String id : deleteParams.getData()) {");
            fileLineList.add("            "+WordUtils.uncapitalize(repoName)+".deleteById(Long.parseLong(id));");
            fileLineList.add("        }");
            fileLineList.add("        return ApiResultBuilder.create().code(ApiResultCode.Success.code()).msg(\"删除成功\").build();");
            fileLineList.add("    }");
            fileLineList.add("");
            fileLineList.add("}");
            fileLineList.add("");

            File distFile = new File(distDir, ctrlName + ".java");
            if (distFile.exists()) {
                distFile.delete();
            }
            RandomAccessFile aFile = new RandomAccessFile(distFile, "rw");
            FileChannel fileChannel = aFile.getChannel();

            byte[] bytes = StringUtils.join(fileLineList, '\n').getBytes("UTF-8");

            ByteBuffer buf= ByteBuffer.allocate(bytes.length);
            buf.clear();

            buf.put(bytes);
            buf.flip();
            while (buf.hasRemaining()) {
                fileChannel.write(buf);
            }

            fileChannel.close();

            System.out.println("----> " + ctrlName + " 完成");

        } catch (Exception e) {
            e.printStackTrace();
        }
    });
}
}

@Component
public class DomainGenerator {

private GenProperties genProperties;

@Autowired
public DomainGenerator(GenProperties genProperties) {
    this.genProperties = genProperties;
}

public void execute() throws Exception {

    String projectDir = this.getClass().getResource("/").getPath().replace("target/classes/", "");
    File distDir = new File(projectDir, "src/main/java/com/test/demoApp/gen/domain");
    System.out.println(distDir);

    genProperties.getDomains().forEach(item -> {

        try{

            List<String> fileLineList = new ArrayList<>();

            String domainClassName = item.getName();

            fileLineList.add("package com.test.demoApp.gen.domain;");
            fileLineList.add("import com.test.demoApp.fixed.domain.*;");
            fileLineList.add("import com.fasterxml.jackson.annotation.JsonIgnore;");
            fileLineList.add("import com.fasterxml.jackson.annotation.JsonIgnoreProperties;");
            fileLineList.add("import org.hibernate.annotations.DynamicInsert;");
            fileLineList.add("import org.hibernate.annotations.DynamicUpdate;");
            fileLineList.add("");
            fileLineList.add("import javax.persistence.*;");
            fileLineList.add("import java.io.Serializable;");
            fileLineList.add("import java.util.*;");
            fileLineList.add("import java.sql.Timestamp;");
            fileLineList.add("import java.math.BigDecimal;");
            fileLineList.add("");
            fileLineList.add("@Entity");
            fileLineList.add("@DynamicUpdate(true)");
            fileLineList.add("@DynamicInsert(true)");
            fileLineList.add("@JsonIgnoreProperties(value = {\"handler\",\"hibernateLazyInitializer\",\"fieldHandler\"})");
            fileLineList.add("@Table(name = \"BIZ_" + domainClassName.toUpperCase() + "\")");
            fileLineList.add("public class " + domainClassName + " extends BaseEntity implements Serializable {");
            fileLineList.add("    private static final long serialVersionUID = 1L;");
            fileLineList.add("");

            List<String> domainFields = item.getFields();
            domainFields.forEach(fieldDef ->{
                String[] fieldInfo = StringUtils.splitPreserveAllTokens(fieldDef, "|");
                String comment = fieldInfo[0];
                String fieldName = fieldInfo[1];
                String fieldType = fieldInfo[2];
                String relation = fieldInfo[3];
                String mainTableFlag = fieldInfo[4];
                fileLineList.add("    /** " + comment + " */");

                if ("ManyToOne".equals(relation)) {
                    fileLineList.add("    @JsonIgnore");
                    fileLineList.add("    @ManyToOne");
                    fileLineList.add("    @JoinColumn(name = \""+fieldName+"_id\")");
                    fileLineList.add("    private " + fieldType + " " + fieldName + ";");
                } else if ("OneToMany".equals(relation)) {
                    fileLineList.add("    @OneToMany(mappedBy = \"parent"+ domainClassName +"\", cascade = CascadeType.ALL, orphanRemoval = true)");
                    if (StringUtils.contains(fieldType, "Set")) {
                        fileLineList.add("    private " + fieldType + " " + fieldName + " = new TreeSet<>();");
                    } else {
                        fileLineList.add("    private " + fieldType + " " + fieldName + " = new ArrayList<>();");
                    }

                } else if("ManyToMany".equals(relation)) {
                    if ("main".equals(mainTableFlag)) {
                        String mainTableName = domainClassName;
                        String slaveTableName = fieldName.replace("List", "");
                        fileLineList.add("    @ManyToMany(fetch = FetchType.EAGER)");
                        fileLineList.add("    @JoinTable(");
                        fileLineList.add("            name=\"" + mainTableName + "_" + slaveTableName + "\",");
                        fileLineList.add("            joinColumns=@JoinColumn(name=\"" + mainTableName + "_ID" + "\", referencedColumnName=\"ID\"),");
                        fileLineList.add("            inverseJoinColumns=@JoinColumn(name=\"" + slaveTableName + "_ID" + "\", referencedColumnName=\"ID\"))");
                        if (StringUtils.contains(fieldType, "Set")) {
                            fileLineList.add("    private " + fieldType + " " + fieldName + " = new TreeSet<>();");
                        } else {
                            fileLineList.add("    private " + fieldType + " " + fieldName + " = new ArrayList<>();");
                        }
                    } else {
                        fileLineList.add("    @JsonIgnore");
                        fileLineList.add("    @ManyToMany(mappedBy=\"" + WordUtils.uncapitalize(domainClassName) + "List" + "\", fetch = FetchType.LAZY)");
                        if (StringUtils.contains(fieldType, "Set")) {
                            fileLineList.add("    private " + fieldType + " " + fieldName + " = new TreeSet<>();");
                        } else {
                            fileLineList.add("    private " + fieldType + " " + fieldName + " = new ArrayList<>();");
                        }
                    }
                } else if ("OneToOne".equals(relation)) {
                    if ("main".equals(mainTableFlag)) {
                        fileLineList.add("    @OneToOne(mappedBy = \""+WordUtils.uncapitalize(domainClassName)+"\", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)");
                        fileLineList.add("    private " + fieldType + " " + fieldName + ";");
                    } else {
                        fileLineList.add("    @JsonIgnore");
                        fileLineList.add("    @OneToOne(fetch = FetchType.LAZY)");
                        fileLineList.add("    @JoinColumn(name = \""+fieldName+"_id\")");
                        fileLineList.add("    private " + fieldType + " " + fieldName + ";");
                    }
                } else {
                    fileLineList.add("    private " + fieldType + " " + fieldName + ";");
                }
            });
            domainFields.forEach(fieldDef ->{
                String[] fieldInfo = StringUtils.splitPreserveAllTokens(fieldDef, "|");
                String comment = fieldInfo[0];
                String fieldName = fieldInfo[1];
                String fieldType = fieldInfo[2];
                String relation = fieldInfo[3];

                // GET方法
                fileLineList.add("    /**");
                fileLineList.add("     * 获取 " + comment);
                fileLineList.add("     *");
                fileLineList.add("     * @return "+fieldName+" "+comment);
                fileLineList.add("     */");
                fileLineList.add("    public "+fieldType+" get"+StringUtils.capitalize(fieldName)+"() {");
                fileLineList.add("        return this."+fieldName+";");
                fileLineList.add("    }");
                fileLineList.add("");

                // SET方法
                fileLineList.add("    /**");
                fileLineList.add("     * 设置 " + comment);
                fileLineList.add("     *");
                fileLineList.add("     * @param "+fieldName+" "+comment);
                fileLineList.add("     */");
                fileLineList.add("    public void set"+StringUtils.capitalize(fieldName)+"("+fieldType+" "+fieldName+") {");
                fileLineList.add("        this."+fieldName+" = "+fieldName+";");
                fileLineList.add("    }");
                fileLineList.add("");
            });
            fileLineList.add("}");

            File distFile = new File(distDir, domainClassName + ".java");
            if (distFile.exists()) {
                distFile.delete();
            }
            RandomAccessFile aFile = new RandomAccessFile(distFile, "rw");
            FileChannel fileChannel = aFile.getChannel();

            byte[] bytes = StringUtils.join(fileLineList, '\n').getBytes("UTF-8");

            ByteBuffer buf= ByteBuffer.allocate(bytes.length);
            buf.clear();

            buf.put(bytes);
            buf.flip();
            while (buf.hasRemaining()) {
                fileChannel.write(buf);
            }

            fileChannel.close();

            System.out.println("----> " + domainClassName + " 完成");
        } catch (Exception e) {
            e.printStackTrace();
        }
    });

}
}

@Component
@ConfigurationProperties(prefix = "gen")
public class GenProperties {

private List<DomainConf> domains;
private List<RepoConf> repositorys;
private List<CtrlConf> controllers;

public GenProperties.DomainConf findDomian(String domainName) {
    for (DomainConf domainConf : domains) {
        if (domainConf.getName().equals(domainName)) {
            return domainConf;
        }
    }
    return null;
}


public List<DomainConf> getDomains() {
    return domains;
}

public void setDomains(List<DomainConf> domains) {
    this.domains = domains;
}

public List<RepoConf> getRepositorys() {
    return repositorys;
}

public void setRepositorys(List<RepoConf> repositorys) {
    this.repositorys = repositorys;
}

public List<CtrlConf> getControllers() {
    return controllers;
}

public void setControllers(List<CtrlConf> controllers) {
    this.controllers = controllers;
}

public static class DomainConf {
    private String name;
    private List<String> fields;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<String> getFields() {
        return fields;
    }

    public void setFields(List<String> fields) {
        this.fields = fields;
    }
}
public static class RepoConf {
    private String name;
    private String domain;
    private String pkType;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDomain() {
        return domain;
    }

    public void setDomain(String domain) {
        this.domain = domain;
    }

    public String getPkType() {
        return pkType;
    }

    public void setPkType(String pkType) {
        this.pkType = pkType;
    }
}
public static class CtrlConf {
    private String name;
    private String domain;
    private String repository;
    private String tags;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDomain() {
        return domain;
    }

    public void setDomain(String domain) {
        this.domain = domain;
    }

    public String getRepository() {
        return repository;
    }

    public void setRepository(String repository) {
        this.repository = repository;
    }

    public String getTags() {
        return tags;
    }

    public void setTags(String tags) {
        this.tags = tags;
    }
}
}

 @Component
 public class RepoGenerator {

private GenProperties genProperties;

@Autowired
public RepoGenerator(GenProperties genProperties) {
    this.genProperties = genProperties;
}

public void execute() throws Exception {
    String projectDir = this.getClass().getResource("/").getPath().replace("target/classes/", "");
    File distDir = new File(projectDir, "src/main/java/com/test/demoApp/gen/repository");
    System.out.println(distDir);

    System.out.println("开始生成");

    genProperties.getRepositorys().forEach(item -> {
        try {
            String domianClassName = item.getDomain();
            String pkType = item.getPkType();

            String repoClassName = domianClassName + "RepositoryDsl";
            if (StringUtils.isNotEmpty(item.getName())) {
                repoClassName = item.getName();
            }

            String[] strings = {
                    "package com.test.demoApp.gen.repository;",
                    "",
                    "import com.test.demoApp.gen.domain."+ domianClassName + ";",
                    "import org.springframework.data.jpa.repository.JpaRepository;",
                    "import org.springframework.data.querydsl.QuerydslPredicateExecutor;",
                    "",
                    "public interface "+ repoClassName +" extends JpaRepository<" + domianClassName + ", " + pkType + ">,QuerydslPredicateExecutor<" + domianClassName + "> {",
                    "}"
            };

            File distFile = new File(distDir, repoClassName + ".java");
            if (distFile.exists()) {
                distFile.delete();
            }
            RandomAccessFile aFile = new RandomAccessFile(distFile, "rw");
            FileChannel fileChannel = aFile.getChannel();

            byte[] bytes = StringUtils.join(strings, '\n').getBytes("UTF-8");

            ByteBuffer buf= ByteBuffer.allocate(bytes.length);
            buf.clear();

            buf.put(bytes);
            buf.flip();
            while (buf.hasRemaining()) {
                fileChannel.write(buf);
            }

            fileChannel.close();

            System.out.println("----> " + repoClassName + " 完成");

        } catch (Exception e) {
            e.printStackTrace();
        }
    });
    System.out.println("生成结束");
}

}

有这几个就可以用了注意一下路劲的配置就行了

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 206,839评论 6 482
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 88,543评论 2 382
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 153,116评论 0 344
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 55,371评论 1 279
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 64,384评论 5 374
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,111评论 1 285
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,416评论 3 400
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,053评论 0 259
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 43,558评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,007评论 2 325
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,117评论 1 334
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,756评论 4 324
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,324评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,315评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,539评论 1 262
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,578评论 2 355
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,877评论 2 345

推荐阅读更多精彩内容