美文网首页
idea表映射pojo+mapper+service+contr

idea表映射pojo+mapper+service+contr

作者: devLiao | 来源:发表于2019-08-07 12:04 被阅读0次

    生成的时候写了一些个性化的东西,需要提前集成好mybatis plus lombok,这些东西。
    (安利一下mybatis plus ,太好用了)

    好,进入正题
    首选在idea 内连接数据库


    image.png

    填好了以后连上以后右边看到一堆表


    image.png

    大概是这个样子

    然后随便找张表右键


    image.png

    然后进入脚本


    image.png

    最开始是有个pojo的,可以直接生成,后面是我自己写的,反正就是做一些个性化的东西没改啥,这里把代码贴出来,也可以根据我的来改

    POJO

    import com.intellij.database.model.DasTable
    import com.intellij.database.util.Case
    import com.intellij.database.util.DasUtil
    
    /*
     * Available context bindings:
     *   SELECTION   Iterable<DasObject>
     *   PROJECT     project
     *   FILES       files helper
     */
    
    packageName = "com.cjkj.sbdcp.domain;"
    typeMapping = [
            (~/(?i)int/)                      : "long",
            (~/(?i)float|double|decimal|real/): "double",
            (~/(?i)datetime|timestamp/)       : "java.sql.Timestamp",
            (~/(?i)date/)                     : "java.sql.Date",
            (~/(?i)time/)                     : "java.sql.Time",
            (~/(?i)/)                         : "String"
    ]
    
    FILES.chooseDirectoryAndSave("Choose directory", "Choose where to store generated files") { dir ->
        SELECTION.filter { it instanceof DasTable }.each { generate(it, dir) }
    }
    
    def generate(table, dir) {
        def className = javaName(table.getName(), true)
        def fields = calcFields(table)
        new File(dir, className + ".java").withPrintWriter { out -> generate(out, className, table.getName(), fields) }
    }
    
    
    def generate(out, className, tableName, fields) {
        out.println "package $packageName"
        out.println ""
        out.println "import com.baomidou.mybatisplus.annotation.TableName;"
        out.println "import lombok.Builder;"
        out.println "import lombok.Data;"
        out.println ""
        out.println "@Data"
        out.println "@Builder"
        out.println "@TableName(\"$tableName\")"
        out.println "public class $className {"
        out.println ""
        fields.each() {
            if (it.annos != "") out.println "  ${it.annos}"
            out.println "    private ${it.type} ${it.name};"
        }
        out.println ""
        out.println "    public $className() {"
        out.println "    }"
        out.println ""
        out.print "    public $className("
    
        StringBuilder stringBuilder = new StringBuilder()
        fields.each() {
            stringBuilder.append("${it.type} ${it.name}, ")
        }
        stringBuilder.delete(stringBuilder.length() -2 , stringBuilder.length())
        out.print stringBuilder
        out.println ") {"
        fields.each() {
            out.println "        this.${it.name} = ${it.name};"
        }
        out.println "    }"
        out.println "}"
    }
    
    def calcFields(table) {
        DasUtil.getColumns(table).reduce([]) { fields, col ->
            def spec = Case.LOWER.apply(col.getDataType().getSpecification())
            def typeStr = typeMapping.find { p, t -> p.matcher(spec).find() }.value
            fields += [[
                               name : javaName(col.getName(), false),
                               type : typeStr,
                               annos: ""]]
        }
    }
    
    def javaName(str, capitalize) {
        def s = com.intellij.psi.codeStyle.NameUtil.splitNameIntoWords(str)
                .collect { Case.LOWER.apply(it).capitalize() }
                .join("")
                .replaceAll(/[^\p{javaJavaIdentifierPart}[_]]/, "_")
        capitalize || s.length() == 1 ? s : Case.LOWER.apply(s[0]) + s[1..-1]
    }
    
    

    Mapper

    import com.intellij.database.model.DasTable
    import com.intellij.database.util.Case
    import com.intellij.database.util.DasUtil
    
    /*
     * Available context bindings:
     *   SELECTION   Iterable<DasObject>
     *   PROJECT     project
     *   FILES       files helper
     */
    
    packageName = "com.cjkj.sbdcp.mapper;"
    typeMapping = [
            (~/(?i)int/)                      : "long",
            (~/(?i)float|double|decimal|real/): "double",
            (~/(?i)datetime|timestamp/)       : "java.sql.Timestamp",
            (~/(?i)date/)                     : "java.sql.Date",
            (~/(?i)time/)                     : "java.sql.Time",
            (~/(?i)/)                         : "String"
    ]
    
    FILES.chooseDirectoryAndSave("Choose directory", "Choose where to store generated files") { dir ->
        SELECTION.filter { it instanceof DasTable }.each { generate(it, dir) }
    }
    
    def generate(table, dir) {
        def className = javaName(table.getName(), true)
        def fields = calcFields(table)
        new File(dir, className + "Mapper.java").withPrintWriter { out -> generate(out, className, table.getName(), fields) }
    }
    def generate(out, className, tableName, fields) {
        out.println "package $packageName"
        out.println ""
        out.println "import com.baomidou.mybatisplus.core.mapper.BaseMapper;"
        out.println "import com.cjkj.sbdcp.domain.$className;"
        out.println "import org.apache.ibatis.annotations.Mapper;"
        out.println "import org.springframework.stereotype.Repository;"
        out.println ""
        out.println "@Repository"
        out.println "@Mapper"
        out.println "public interface " + className + "Mapper extends BaseMapper<$className> {"
        out.println "}"
    }
    
    def calcFields(table) {
        DasUtil.getColumns(table).reduce([]) { fields, col ->
            def spec = Case.LOWER.apply(col.getDataType().getSpecification())
            def typeStr = typeMapping.find { p, t -> p.matcher(spec).find() }.value
            fields += [[
                               name : javaName(col.getName(), false),
                               type : typeStr,
                               annos: ""]]
        }
    }
    
    def javaName(str, capitalize) {
        def s = com.intellij.psi.codeStyle.NameUtil.splitNameIntoWords(str)
                .collect { Case.LOWER.apply(it).capitalize() }
                .join("")
                .replaceAll(/[^\p{javaJavaIdentifierPart}[_]]/, "_")
        capitalize || s.length() == 1 ? s : Case.LOWER.apply(s[0]) + s[1..-1]
    }
    
    

    Service

    import com.intellij.database.model.DasTable
    import com.intellij.database.util.Case
    import com.intellij.database.util.DasUtil
    
    /*
     * Available context bindings:
     *   SELECTION   Iterable<DasObject>
     *   PROJECT     project
     *   FILES       files helper
     */
    
    packageName = "com.cjkj.sbdcp.service;"
    typeMapping = [
            (~/(?i)int/)                      : "long",
            (~/(?i)float|double|decimal|real/): "double",
            (~/(?i)datetime|timestamp/)       : "java.sql.Timestamp",
            (~/(?i)date/)                     : "java.sql.Date",
            (~/(?i)time/)                     : "java.sql.Time",
            (~/(?i)/)                         : "String"
    ]
    
    FILES.chooseDirectoryAndSave("Choose directory", "Choose where to store generated files") { dir ->
        SELECTION.filter { it instanceof DasTable }.each { generate(it, dir) }
    }
    
    def generate(table, dir) {
        def className = javaName(table.getName(), true)
        def fields = calcFields(table)
        new File(dir, className + "Service.java").withPrintWriter { out -> generate(out, className, table.getName(), fields) }
    }
    
    def generate(out, className, tableName, fields) {
        out.println "package $packageName"
        out.println ""
        out.println "import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;"
        out.println "import com.cjkj.sbdcp.domain.$className;"
        out.println "import com.cjkj.sbdcp.mapper.dcp." + className + "Mapper;"
        out.println "import org.springframework.stereotype.Service;"
        out.println ""
        out.println "@Service"
        out.println "public class " + className + "Service extends ServiceImpl<" + className + "Mapper,$className> {"
        out.println "}"
    }
    
    def calcFields(table) {
        DasUtil.getColumns(table).reduce([]) { fields, col ->
            def spec = Case.LOWER.apply(col.getDataType().getSpecification())
            def typeStr = typeMapping.find { p, t -> p.matcher(spec).find() }.value
            fields += [[
                               name : javaName(col.getName(), false),
                               type : typeStr,
                               annos: ""]]
        }
    }
    
    def javaName(str, capitalize) {
        def s = com.intellij.psi.codeStyle.NameUtil.splitNameIntoWords(str)
                .collect { Case.LOWER.apply(it).capitalize() }
                .join("")
                .replaceAll(/[^\p{javaJavaIdentifierPart}[_]]/, "_")
        capitalize || s.length() == 1 ? s : Case.LOWER.apply(s[0]) + s[1..-1]
    }
    
    
    

    Controller

    import com.intellij.database.model.DasTable
    import com.intellij.database.util.Case
    import com.intellij.database.util.DasUtil
    
    /*
     * Available context bindings:
     *   SELECTION   Iterable<DasObject>
     *   PROJECT     project
     *   FILES       files helper
     */
    
    packageName = "com.cjkj.sbdcp.controller;"
    typeMapping = [
            (~/(?i)int/)                      : "long",
            (~/(?i)float|double|decimal|real/): "double",
            (~/(?i)datetime|timestamp/)       : "java.sql.Timestamp",
            (~/(?i)date/)                     : "java.sql.Date",
            (~/(?i)time/)                     : "java.sql.Time",
            (~/(?i)/)                         : "String"
    ]
    
    FILES.chooseDirectoryAndSave("Choose directory", "Choose where to store generated files") { dir ->
        SELECTION.filter { it instanceof DasTable }.each { generate(it, dir) }
    }
    
    def generate(table, dir) {
        def className = javaName(table.getName(), true)
        def fields = calcFields(table)
        new File(dir, className + "Controller.java").withPrintWriter { out -> generate(out, className, table.getName(), fields) }
    }
    
    def generate(out, className, tableName, fields) {
        out.println "package $packageName"
        out.println ""
        out.println "import com.cjkj.sbdcp.common.annotation.CrossOriginRestController;"
        out.println "import org.apache.shiro.authz.annotation.RequiresPermissions;"
        out.println "import org.springframework.web.bind.annotation.RequestBody;"
        out.println "import org.springframework.web.bind.annotation.RequestMapping;"
        out.println "import org.springframework.web.bind.annotation.RequestMethod;"
        out.println "import com.cjkj.sbdcp.common.BaseResult;"
        out.println "import com.cjkj.sbdcp.common.BaseController;"
        out.println "import com.cjkj.sbdcp.domain.$className;"
        def model = ""
        if (className.indexOf("Dss") > -1) {
            model = "dss"
            out.println "import com.cjkj.sbdcp.service.dss." + className + "Service;"
        } else if (className.indexOf("Sgf") > -1) {
            model = "sgf"
            out.println "import com.cjkj.sbdcp.service.sgf." + className + "Service;"
        } else if (className.indexOf("Ws") > -1) {
            model = "sgf"
            out.println "import com.cjkj.sbdcp.service.ws." + className + "Service;"
        } else if (className.indexOf("sys") > -1) {
            model = "sys"
            out.println "import com.cjkj.sbdcp.service.system." + className + "Service;"
        } else {
            out.println "import com.cjkj.sbdcp.service." + className + "Service;"
        }
        def javaClassName = className.substring(0, 1).toLowerCase() + className.substring(1, className.length())
        out.println ""
        out.println "@CrossOriginRestController(\"" + model + "/" + javaClassName + "\")"
        out.println "public class " + className + "Controller extends BaseController<" + className + "Service,$className> {"
        out.println ""
        out.println "    @RequiresPermissions(\"" + javaClassName + ":list\")"
        out.println "    @RequestMapping(value = \"list\", method = RequestMethod.GET)"
        out.println "    public BaseResult list() {"
        out.println "        return super.list();"
        out.println "    }"
        out.println ""
        out.println "    @RequiresPermissions(\"" + javaClassName + ":list\")"
        out.println "    @RequestMapping(value = \"list\", method = RequestMethod.POST)"
        out.println "    public BaseResult list(@RequestBody " + className + " " + javaClassName + ") {"
        out.println "        return super.list(" + javaClassName + ");"
        out.println "    }"
        out.println ""
        out.println "    @RequiresPermissions(\"" + javaClassName + ":add\")"
        out.println "    @RequestMapping(value = \"save\", method = RequestMethod.POST)"
        out.println "    public BaseResult save(@RequestBody " + className + " " + javaClassName + ") {"
        out.println "        return super.save(" + javaClassName + ");"
        out.println "    }"
        out.println ""
        out.println "    @RequiresPermissions(\"" + javaClassName + ":update\")"
        out.println "    @RequestMapping(value = \"save\", method = RequestMethod.PUT)"
        out.println "    public BaseResult update(@RequestBody " + className + " " + javaClassName + ") {"
        out.println "        return super.updateById(" + javaClassName + ");"
        out.println "    }"
        out.println ""
        out.println "    @RequiresPermissions(\"" + javaClassName + ":delete\")"
        out.println "    @RequestMapping(value = \"del\", method = RequestMethod.DELETE)"
        out.println "    public BaseResult delete(Long id) {"
        out.println "        return super.deleteById(id);"
        out.println "    }"
        out.println ""
        out.println ""
        out.println "}"
    }
    
    def calcFields(table) {
        DasUtil.getColumns(table).reduce([]) { fields, col ->
            def spec = Case.LOWER.apply(col.getDataType().getSpecification())
            def typeStr = typeMapping.find { p, t -> p.matcher(spec).find() }.value
            fields += [[
                               name : javaName(col.getName(), false),
                               type : typeStr,
                               annos: ""]]
        }
    }
    
    def javaName(str, capitalize) {
        def s = com.intellij.psi.codeStyle.NameUtil.splitNameIntoWords(str)
                .collect { Case.LOWER.apply(it).capitalize() }
                .join("")
                .replaceAll(/[^\p{javaJavaIdentifierPart}[_]]/, "_")
        capitalize || s.length() == 1 ? s : Case.LOWER.apply(s[0]) + s[1..-1]
    }
    
    
    

    BaseController

    
    public class BaseController<S extends ServiceImpl<?, T>, T> {
        
        @Autowired
        protected S s;
        
        public BaseResult list() {
            return BaseResult.createSuccResult().addData("list", s.list(null));
        }
        
        public BaseResult list(T t) {
            return BaseResult.createSuccResult().addData("list", s.list(new QueryWrapper<T>().setEntity(t)));
        }
        
        public BaseResult page(int current, int size) {
            return BaseResult.createSuccResult().addData("page", s.page(new Page<>(current, size), null));
        }
        
        public BaseResult page(T t, int current, int size) {
            return BaseResult.createSuccResult().addData("page", s.page(new Page<>(current, size), new QueryWrapper<T>().setEntity(t)));
        }
        
        public BaseResult save(T t) {
            CommonUtils.insertFilter(t);
            s.save(t);
            return BaseResult.createSuccResult();
        }
        
        public BaseResult saveBatch(Collection<T> ts){
            ts.forEach(t -> {
                CommonUtils.insertFilter(t);
                s.save(t);
            });
            return BaseResult.createSuccResult();
        }
        
        public BaseResult updateById(T t) {
            CommonUtils.updateFilter(t);
            s.updateById(t);
            return BaseResult.createSuccResult();
        }
        
        public BaseResult deleteById(long id) {
            s.removeById(id);
            return BaseResult.createSuccResult();
        }
        
    }
    

    现在是每生成一个层的类要点一下,下个版本整合一下所有的生成和路径选择

    相关文章

      网友评论

          本文标题:idea表映射pojo+mapper+service+contr

          本文链接:https://www.haomeiwen.com/subject/ruandctx.html