使用idea通过Generate POJOs.groovy 生成实体类

首先来张生成的POJO效果图:

数据库表结构如下:

create table tb_demo
(
	id int(10) auto_increment comment '主键'
		primary key,
	username varchar(50) null comment '用户名',
	apply_status tinyint(2) null comment '申请状态:0 未处理 1 申请成功 2 申请失败',
	process_time datetime null comment '处理时间',
	total_amount decimal(10,4) null comment '总金额',
	created_at datetime not null comment '创建时间',
	created_by int(10) null comment '创建人',
	last_updated_at datetime not null comment '最后更新时间',
	last_updated_by int(10) null comment '最后更新人'
)
comment '测试表'
;

groovy脚本如下:

import com.intellij.database.model.DasTable
import com.intellij.database.util.Case
import com.intellij.database.util.DasUtil
import java.text.SimpleDateFormat

/*
 * Available context bindings:
 *   SELECTION   Iterable<DasObject>
 *   PROJECT     project
 *   FILES       files helper
 */

packageName = ""
typeMapping = [
        (~/(?i)tinyint|smallint|mediumint|int/)    : "Integer",
        (~/(?i)bigint/)                         : "Long",
        (~/(?i)float|double|real/)            : "Double",
        (~/(?i)decimal/)                       :"BigDecimal",
        (~/(?i)datetime/)                      : "LocalDateTime",
        (~/(?i)timestamp/)                     : "Instant",
        (~/(?i)date/)                           : "LocalDate",
        (~/(?i)time/)                           : "LocalTime",
        (~/(?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 }.each { generate(it, dir) }
}

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

def generate(table,out, className, fields) {
  out.println "package $packageName"
  out.println ""
  out.println "import javax.persistence.Column;"
  out.println "import javax.persistence.Entity;"
  out.println "import javax.persistence.Table;"
  out.println "import java.io.Serializable;"
  out.println "import lombok.Data;"

  Set<String> importTypes = []

  fields.each() {
    if (it.type != "") {
      if (it.type == "BigDecimal" || it.type == "LocalDateTime" || it.type == "Instant"
              || it.type == "LocalDate" || it.type == "LocalTime"|| it.type == "InputStream")
        importTypes += it.type
    }
  }

  if(importTypes.size()>0){
    importTypes.forEach{
      if (it == 'BigDecimal') out.println("import java.math.BigDecimal;")
      if (it == 'LocalDateTime') out.println("import java.time.LocalDateTime;")
      if (it == 'Instant') out.println("import java.time.Instant;")
      if (it == 'LocalDate') out.println("import java.time.LocalDate;")
      if (it == 'LocalTime') out.println("import java.time.LocalTime;")
      if (it == 'InputStream') out.println("import java.io.InputStream;")
    }
  }

  out.println ""
  out.println ""
  out.println "/**\n" +
          " * @Description  \n" +
          " * @Author  hugangquan\n" +
          " * @Date "+ new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + " \n" +
          " */"
  out.println "@Data"
  out.println "@Entity"
  out.println "@Table( name =\""+table.getName() +"\" )"
  out.println "public class $className implements Serializable {"
  out.println ""
  out.println genSerialID()
  fields.each() {
    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};"
  }

  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
    def comm =[
            spec: spec,
            colName : col.getName(),
            name :  javaName(col.getName(), false),
            type : typeStr,
            commoent: col.getComment(),
            annos: "\t@Column(name = \""+col.getName()+"\",columnDefinition=\"${spec}\" )"]
    if("id".equals(Case.LOWER.apply(col.getName())))
      comm.annos +=["@Id"]
    fields += [comm]
  }
}

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]
}

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

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

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

执行Generate POJOs.groovy,生成的实体类如下:

package com.ruigu.rtms.gateway;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import java.io.Serializable;
import lombok.Data;
import java.time.LocalDateTime;
import java.math.BigDecimal;


/**
 * @Description  
 * @Author  hugangquan
 * @Date 2021-01-05 
 */
@Data
@Entity
@Table ( name ="tb_demo" )
public class TbDemoEntity implements Serializable {

	private static final long serialVersionUID =  1832778359932523628L;

	/**
	 * 主键
	 */
   	@Column(name = "id",columnDefinition="int(10)" )
	private Integer idEntity;

	/**
	 * 用户名
	 */
   	@Column(name = "username",columnDefinition="varchar(50)" )
	private String usernameEntity;

	/**
	 * 申请状态:0 未处理 1 申请成功 2 申请失败
	 */
   	@Column(name = "apply_status",columnDefinition="tinyint(2)" )
	private Integer applyStatusEntity;

	/**
	 * 处理时间
	 */
   	@Column(name = "process_time",columnDefinition="datetime" )
	private LocalDateTime processTimeEntity;

	/**
	 * 总金额
	 */
   	@Column(name = "total_amount",columnDefinition="decimal(10,4)" )
	private BigDecimal totalAmountEntity;

	/**
	 * 创建时间
	 */
   	@Column(name = "created_at",columnDefinition="datetime" )
	private LocalDateTime createdAtEntity;

	/**
	 * 创建人
	 */
   	@Column(name = "created_by",columnDefinition="int(10)" )
	private Integer createdByEntity;

	/**
	 * 最后更新时间
	 */
   	@Column(name = "last_updated_at",columnDefinition="datetime" )
	private LocalDateTime lastUpdatedAtEntity;

	/**
	 * 最后更新人
	 */
   	@Column(name = "last_updated_by",columnDefinition="int(10)" )
	private Integer lastUpdatedByEntity;

}

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值