使用idea自動生成bean文件

之前使用mybatis+mysql的時候,利用generater插件生成代碼。

現在公司使用JPA+sqlserver進行開發。很刺激,換了數據庫之後就不知道該怎麼寫代碼了。建表之後重新生成bean。網上搜了一下發現idea可以直接生成bean文件。

一、連接數據庫

idea連接數據庫,方法基本一樣,如圖:

 

二、創建bean文件夾

三、生成Extensions

打開連接好的數據庫,數據庫操作界面空白處右擊選擇Scripted Extensions-->Go to scripts Directory。如圖:

結果如下:

打開生成的Generate POJOs.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

//此處配置你的entity文件路徑
packageName = "com.ier.dcfilter.entity;"
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 && it.getKind() == ObjectKind.TABLE }.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, table,className, fields) }
}

def generate(out, table,className, fields) {
  def tableName = table.getName()
  out.println "package $packageName"
  out.println ""
  out.println ""
  out.println "import javax.persistence.*;"
  out.println "import java.io.Serializable;"
  out.println "import org.hibernate.annotations.GenericGenerator;"
  out.println ""
  out.println ""
  out.println "@Entity"
  out.println "@Table(name = \"$tableName\")"
  out.println "public class $className implements Serializable{"
  out.println ""
  fields.each() {
    if (it.annos != "") out.println "  ${it.annos}"
    out.println "    private ${it.type} ${it.name};"
  }
  out.println ""



  fields.each() {
      out.println ""
      //我這裏只是爲了判斷id屬性,可以不判斷
      if ("id".equalsIgnoreCase(it.colum)){
        out.println "\t@Id"
        out.println "\t@GenericGenerator(name = \"user-uuid\", strategy = \"uuid\")"
        out.println "\t@GeneratedValue(generator = \"user-uuid\")"
        out.println "\t@Column(name = \"id\", nullable = false, length = 32)"
        out.println "    public ${it.type} get${it.name.capitalize()}() {"
        out.println "        return ${it.name};"
        out.println "    }"
        out.println ""
        out.println "    public void set${it.name.capitalize()}(${it.type} ${it.name}) {"
        out.println "        this.${it.name} = ${it.name};"
        out.println "    }"
        out.println ""
      }else {
        out.println "\t@Column(name = \"${it.colum}\")"
        out.println "    public ${it.type} get${it.name.capitalize()}() {"
        out.println "        return ${it.name};"
        out.println "    }"
        out.println ""
        out.println "    public void set${it.name.capitalize()}(${it.type} ${it.name}) {"
        out.println "        this.${it.name} = ${it.name};"
        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),
                       colum: col.getName(),
                       type : typeStr,
                       annos: ""]]
  }
}

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

四、代碼生成

數據庫操作界面,右擊空白處,依次選擇Scripted Extensions-->Generate POJOs.groovy,選擇自己設置的bean文件路徑,生成代碼。如圖:

效果如下:

package com.ier.dcfilter.entity;


import javax.persistence.*;
import java.io.Serializable;
import org.hibernate.annotations.GenericGenerator;



@Entity
@Table(name = "dcf_base_freq")
public class BaseFreq implements Serializable{


    private static final long serialVersionUID = 1L;
    private String id;
    private String projectId;
    private double freq0;
    private double ho;
    private java.sql.Timestamp time;


	@Id
	@GenericGenerator(name = "user-uuid", strategy = "uuid")
	@GeneratedValue(generator = "user-uuid")
	@Column(name = "id", nullable = false, length = 32)
    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }


	@Column(name = "project_id")
    public String getProjectId() {
        return projectId;
    }

    public void setProjectId(String projectId) {
        this.projectId = projectId;
    }


	@Column(name = "freq0")
    public double getFreq0() {
        return freq0;
    }

    public void setFreq0(double freq0) {
        this.freq0 = freq0;
    }


	@Column(name = "ho")
    public double getHo() {
        return ho;
    }

    public void setHo(double ho) {
        this.ho = ho;
    }


	@Column(name = "time")
    public java.sql.Timestamp getTime() {
        return time;
    }

    public void setTime(java.sql.Timestamp time) {
        this.time = time;
    }

}

五、參考文章

  1. https://www.jianshu.com/p/44bb7e25f5c7

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章