這篇文章主要講解了“idea快速生成entity、dao、service的方法”,文中的講解內(nèi)容簡單清晰,易于學(xué)習(xí)與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學(xué)習(xí)“idea快速生成entity、dao、service的方法”吧!
為大同等地區(qū)用戶提供了全套網(wǎng)頁設(shè)計制作服務(wù),及大同網(wǎng)站建設(shè)行業(yè)解決方案。主營業(yè)務(wù)為網(wǎng)站制作、成都做網(wǎng)站、大同網(wǎng)站設(shè)計,以傳統(tǒng)方式定制建設(shè)網(wǎng)站,并提供域名空間備案等一條龍服務(wù),秉承以專業(yè)、用心的態(tài)度為用戶提供真誠的服務(wù)。我們深信只要達到每一位用戶的要求,就會得到認可,從而選擇與我們長期合作。這樣,我們也可以走得更遠!
經(jīng)常寫一些業(yè)務(wù)代碼,學(xué)會快速生成項目上業(yè)務(wù)代碼所需的類entity、dao、service類對我們提高工作效率很有幫助,整理步驟如下:
在idea中連接數(shù)據(jù)庫
下載idea的CodeMaker插件
準備生成實體類的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* 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格式然后移動到項目目錄中入圖所示:
接下來就可以直接在idea右側(cè)database中對需要生成實體類的表執(zhí)行腳本了,如圖所示,點擊右側(cè)的database-選擇表右鍵-選擇scripted-Extensions-然后選擇添加的腳本
之后選擇生成的目錄為entity目錄:
之后類就生成好了:
其中繼承的類,引入的包,注解都可以在腳本中修改。
與實體生成不一樣,這里使用codemaker插件功能生成。先在codemaker中添加模板。 進入settings,搜索codemaker,進入codemaker相關(guān)配置項。
添加所需要的模板,以生成Dao為例:上面只需要改className,這里寫入${class0.className}Dao,表示取輸入的類的類名后面加個Dao
模板代碼也是使用現(xiàn)成的,自己根據(jù)需要猜著改就行,模板代碼如下: dao/mapper模板:
######################################################################################## ## ## 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)-選擇對應(yīng)模板-然后選擇生成目錄:
這里好像只能生成在entity同目錄,不能選擇其他目錄,需要我們移動到對應(yīng)的包。 生成后的dao如圖所示:
至此,代碼就生成完畢了,這個方法讓自己初次接觸到了groovy腳本,不過還是不會怎么用,不過湊合復(fù)制粘貼別人的腳本也能改改。先就這樣吧,以后遇到相關(guān)該腳本的問題再百度。
感謝各位的閱讀,以上就是“idea快速生成entity、dao、service的方法”的內(nèi)容了,經(jīng)過本文的學(xué)習(xí)后,相信大家對idea快速生成entity、dao、service的方法這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是創(chuàng)新互聯(lián),小編將為大家推送更多相關(guān)知識點的文章,歡迎關(guān)注!