温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

idea怎么根据数据库表自动生成JPA实体类

发布时间:2021-06-25 18:00:23 来源:亿速云 阅读:866 作者:chen 栏目:大数据

本篇内容主要讲解“idea怎么根据数据库表自动生成JPA实体类”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“idea怎么根据数据库表自动生成JPA实体类”吧!

在一些软件开发过程模式下,可能会需要根据数据库表生成对应的实体。在idea工具中如何做到这点呢?最简单的答案可能是使用插件吧。其实还有一个很快捷的方法,步骤如下:

  1. 通过view->tool windows->database菜单,打开数据库工具

  2. 连接数据库

  3. 选定需要生成实体类的表,右键菜单选择scripted extensions,有一个Generate POJOs.groovy

如此生成的实体类也许不能满足你的需求,你可以自己写一个groovy脚本来生成符合需求的实体类。在上面的第三步中,下面有一个go to scripts directory菜单,即可打开脚本目录。在此目录下新建一个脚本,比如Generate jpa Entity Object.groovy。

比如我创建的脚本如下

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 = "me.test.entity;"
typeMapping = [
        (~/(?i)bigint/)                   : "Long",
        (~/(?i)tinyint/)                  : "Boolean",
        (~/(?i)int/)                      : "Integer",
        (~/(?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, fields, table) }
}

def generate(out, className, fields, table) {
  out.println "package $packageName"
  out.println ""
  out.println "import lombok.Data;"
  out.println "import javax.persistence.*;"
  out.println ""
  out.println "/**"
  out.println " * entity class for ${table.getName()}"
  if (isNotEmpty(table.getComment())) {
    out.println " * ${table.getComment()}"
  }
  out.println "*/"
  out.println "@Data"
  out.println "@Entity"
  out.println "@Table(name = \"${table.getName()}\")"
  out.println "public class $className {"
  out.println ""
  fields.each() {
    out.println "\t/**"
    out.println "\t* ${isNotEmpty(it.comment) ? it.comment : it.name}"
    out.println "\t*/"
    if (it.annos.size() > 0)
      it.annos.each() {
        out.println "\t${it}"
      }
    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 anos = [];
    if (Case.LOWER.apply(col.getName()).equals('id')) {
      anos += ["@Id", "@GeneratedValue(strategy = GenerationType.IDENTITY)"]
    } else {
      anos += ["@Column(name = \"${col.getName()}\")"]
    }
    def field = [
            name : javaName(col.getName(), false),
            type : typeStr,
            comment: col.getComment(),
            annos: anos]
    fields += [field]
  }
}

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


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('')
  }
}

到此,相信大家对“idea怎么根据数据库表自动生成JPA实体类”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI