idea快速生成entity、dao、service

常常寫一些業務代碼,學會快速生成項目上業務代碼所需的類entity、dao、service類對咱們提升工做效率頗有幫助,整理步驟以下:java

1、準備工做

  1. 在idea中鏈接數據庫
  2. 下載idea的CodeMaker插件

2、生成實體類

準備生成實體類的groovy腳本,這裏我直接用寫好了的腳本,由於不懂groovy,只能是在腳本上猜着改改,但實體類生成都差很少,猜着改改勉強能改到知足本身要求,下面把腳本貼上:數據庫

import com.intellij.database.model.DasTable
import com.intellij.database.model.ObjectKind
import com.intellij.database.util.Case
import com.intellij.database.util.DasUtil
import java.io.*
import java.text.SimpleDateFormat
import java.lang.*;

/*
 * Available context bindings:
 *   SELECTION   Iterable<DasObject>
 *   PROJECT     project
 *   FILES       files helper
 */
packageName = ""
typeMapping = [
        (~/(?i)bigint/)                             : "Long",
        (~/(?i)int|tinyint|smallint|mediumint/)      : "Integer",

        (~/(?i)bool|bit/)                        : "Boolean",
        (~/(?i)float|double|decimal|real/)       : "Double",
        (~/(?i)datetime|timestamp|date|time/)    : "Date",
        (~/(?i)blob|binary|bfile|clob|raw|image/): "InputStream",
        (~/(?i)/)                                : "String"
]


FILES.chooseDirectoryAndSave("Choose directory", "Choose where to store generated files") { dir ->
  SELECTION.filter { it instanceof DasTable && it.getKind() == ObjectKind.TABLE }.each { generate(it, dir) }
}

def generate(table, dir) {
  def className = javaName(table.getName(), true)
  def fields = calcFields(table)
  packageName = getPackageName(dir)
  PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(new File(dir, className + ".java")), "UTF-8"))
  printWriter.withPrintWriter {out -> generate(out, className, fields,table)}

//    new File(dir, className + ".java").withPrintWriter { out -> generate(out, className, fields,table) }
}

// 獲取包所在文件夾路徑
def getPackageName(dir) {
  return dir.toString().replaceAll("\\\\", ".").replaceAll("/", ".").replaceAll("^.*src(\\.main\\.java\\.)?", "") + ";"
}

def generate(out, className, fields,table) {
  out.println "package $packageName"
  out.println ""
  out.println "import com.yunhuakeji.component.base.annotation.doc.ApiField;"
  out.println "import com.yunhuakeji.component.base.annotation.entity.Code;"
  out.println "import com.yunhuakeji.component.base.bean.entity.base.BaseEntity;"
  out.println "import com.yunhuakeji.component.base.enums.entity.YesNoCodeEnum;"
  out.println "import lombok.Getter;"
  out.println "import lombok.Setter;"
  out.println "import lombok.ToString;"
  out.println "import io.swagger.annotations.ApiModel;"
  out.println "import io.swagger.annotations.ApiModelProperty;"
  out.println "import java.time.LocalDateTime;"
  out.println "import javax.persistence.Table;"
  out.println "import javax.persistence.Column;"
  //out.println "import import java.util.Date;"


  Set types = new HashSet()

  fields.each() {
    types.add(it.type)
  }

  if (types.contains("Date")) {
    out.println "import java.time.LocalDateTime;"
  }

  if (types.contains("InputStream")) {
    out.println "import java.io.InputStream;"
  }
  out.println ""
  out.println "/**\n" +
          " * @Description  \n" +
          " * @Author  chenzhicong\n" +
          " * @Date "+ new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + " \n" +
          " */"
  out.println ""
  out.println "@Setter"
  out.println "@Getter"
  out.println "@ToString"
  out.println "@Table ( name =\""+table.getName() +"\" )"
  out.println "public class $className  extends BaseEntity {"
  out.println ""
  out.println genSerialID()
  fields.each() {
    if(!"universityId".equals(it.name)&&
            !"operatorId".equals(it.name)&&
            !"createdDate".equals(it.name)&&
            !"state".equals(it.name)&&
            !"stateDate".equals(it.name)&&
            !"memo".equals(it.name)){
      out.println ""
      // 輸出註釋
      if (isNotEmpty(it.commoent)) {
        out.println "\t/**"
        out.println "\t * ${it.commoent.toString()}"
        out.println "\t */"
      }

      if (it.annos != "") out.println "   ${it.annos.replace("[@Id]", "")}"

      // 輸出成員變量

      out.println "\tprivate ${it.type} ${it.name};"
    }

  }

  // 輸出get/set方法
//    fields.each() {
//        out.println ""
//        out.println "\tpublic ${it.type} get${it.name.capitalize()}() {"
//        out.println "\t\treturn this.${it.name};"
//        out.println "\t}"
//        out.println ""
//
//        out.println "\tpublic void set${it.name.capitalize()}(${it.type} ${it.name}) {"
//        out.println "\t\tthis.${it.name} = ${it.name};"
//        out.println "\t}"
//    }
  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
    if("Date".equals(typeStr)){
      typeStr="LocalDateTime"
    }

    if(col.getName().toString().startsWith("PK_")){
      typeStr = "Long"
    }



    def comm =[
            colName : col.getName(),
            name :  javaName(col.getName(), false),
            type : typeStr,
            commoent: col.getComment(),
            annos: "\t@Column(name = \""+col.getName()+"\" )"]
    if(isNotEmpty(col.getComment())){
      comm.annos +="\r\n\t@ApiField(desc = \""+col.getComment()+"\")"
    }
 /*   if(col.getComment().startsWith("pk_")){
      comm.annos +="\r\n\t@Id"
    }*/


    if(Case.LOWER.apply(comm.name.toString()).startsWith("pk")){
      comm.annos +="\r\n\t@Id"
    }
    if("id".equals(Case.LOWER.apply(col.getName()))){
      comm.annos +=["@Id"]}
    fields += [comm]
  }
}

// 處理類名(這裏是由於個人表都是以t_命名的,因此須要處理去掉生成類名時的開頭的T,
// 若是你不須要那麼請查找用到了 javaClassName這個方法的地方修改成 javaName 便可)
def javaClassName(str, capitalize) {
  def s = com.intellij.psi.codeStyle.NameUtil.splitNameIntoWords(str)
          .collect { Case.LOWER.apply(it).capitalize() }
          .join("")
          .replaceAll(/[^\p{javaJavaIdentifierPart}[_]]/, "_")
  // 去除開頭的T  http://developer.51cto.com/art/200906/129168.htm
  s = s[1..s.size()-1]
  capitalize || s.length() == 1? s : Case.LOWER.apply(s[0]) + s[1..-1]
}

def javaName(str, capitalize) {
//    def s = str.split(/(?<=[^\p{IsLetter}])/).collect { Case.LOWER.apply(it).capitalize() }
//            .join("").replaceAll(/[^\p{javaJavaIdentifierPart}]/, "_")
//    capitalize || s.length() == 1? s : Case.LOWER.apply(s[0]) + s[1..-1]
  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]
}

def isNotEmpty(content) {
  return content != null && content.toString().trim().length() > 0
}

static String changeStyle(String str, boolean toCamel){
  if(!str || str.size() <= 1)
    return str

  if(toCamel){
    String r = str.toLowerCase().split('_').collect{cc -> Case.LOWER.apply(cc).capitalize()}.join('')
    return r[0].toLowerCase() + r[1..-1]
  }else{
    str = str[0].toLowerCase() + str[1..-1]
    return str.collect{cc -> ((char)cc).isUpperCase() ? '_' + cc.toLowerCase() : cc}.join('')
  }
}

static String genSerialID()
{
  return "\tprivate static final long serialVersionUID =  "+Math.abs(new Random().nextLong())+"L;"
}

把腳本保存爲groovy格式而後移動到項目目錄中入圖所示:api

接下來就能夠直接在idea右側database中對須要生成實體類的表執行腳本了,如圖所示,點擊右側的database-選擇表右鍵-選擇scripted-Extensions-而後選擇添加的腳本app

以後選擇生成的目錄爲entity目錄: dom

以後類就生成好了:ide

其中繼承的類,引入的包,註解均可以在腳本中修改。this

3、生成service、serviceImpL和dao

與實體生成不同,這裏使用codemaker插件功能生成。先在codemaker中添加模板。 進入settings,搜索codemaker,進入codemaker相關配置項。idea

添加所須要的模板,以生成Dao爲例:上面只須要改className,這裏寫入${class0.className}Dao,表示取輸入的類的類名後面加個Dao插件

模板代碼也是使用現成的,本身根據須要猜着改就行,模板代碼以下: dao/mapper模板:3d

########################################################################################
##
## Common variables:
##  $YEAR - yyyy
##  $TIME - yyyy-MM-dd HH:mm:ss
##  $USER - 陳之聰
##
## Available variables:
##  $class0 - the context class, alias: $class
##  $class1 - the selected class, like $class1, $class2
##  $ClassName - generate by the config of "Class Name", the generated class name
##
## Class Entry Structure:
##  $class0.className - the class Name
##  $class0.packageName - the packageName
##  $class0.importList - the list of imported classes name
##  $class0.fields - the list of the class fields
##          - type: the field type
##          - name: the field name
##          - modifier: the field modifier, like "private",or "@Setter private" if include annotations
##  $class0.allFields - the list of the class fields include all fields of superclass
##          - type: the field type
##          - name: the field name
##          - modifier: the field modifier, like "private",or "@Setter private" if include annotations
##  $class0.methods - the list of class methods
##          - name: the method name
##          - modifier: the method modifier, like "private static"
##          - returnType: the method returnType
##          - params: the method params, like "(String name)"
##  $class0.allMethods - the list of class methods include all methods of superclass
##          - name: the method name
##          - modifier: the method modifier, like "private static"
##          - returnType: the method returnType
##          - params: the method params, like "(String name)"#
########################################################################################
package $class0.PackageName;

import com.mapper.GeneralMapper;


/**
 *
 * @author chenzhicong
 * @version $Id: ${ClassName}.java, v 0.1 $TIME $USER Exp $$
 */
public interface  $ClassName extends GeneralMapper<${class0.className}>{



}

service、serviceImpl操做方法相似,就不贅述了,按照上面的方法分別創建模板就行。

模板創建好了以後,咱們就只須要在剛剛生成的實體類中按快捷鍵Alt+Insert(或者右鍵-Generate)-選擇對應模板-而後選擇生成目錄:

這裏好像只能生成在entity同目錄,不能選擇其餘目錄,須要咱們移動到對應的包。 生成後的dao如圖所示:

總結

至此,代碼就生成完畢了,這個方法讓本身初次接觸到了groovy腳本,不過仍是不會怎麼用,不過湊合複製粘貼別人的腳本也能改改。先就這樣吧,之後遇到相關該腳本的問題再百度。

相關文章
相關標籤/搜索