侧边栏壁纸
博主头像
威风博主等级

九万里风鹏正举,风休住,蓬舟吹取三山去。

  • 累计撰写 38 篇文章
  • 累计创建 23 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录

SpringDataJpa实体类自动生成

威风
2020-09-17 / 0 评论 / 0 点赞 / 225 阅读 / 3,682 字 / 正在检测是否收录...
温馨提示:
本文最后更新于 2021-11-06,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

Spring Data Jpa实体类idea自动生成

1. idea连接数据库

  1. 点击Database idea右侧

    image-20200713174146466

  2. 点击+ 号->Data Source -> MySql (这里选择你的数据库)

    image-20200713174235357

  3. 按照提示填写信息

    image-20200713174447102

  4. 连接成功后即可看到你的数据库情况

    image-20200713174530716

2 建立基本项目 导入依赖

image-20200713174742197

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <!-- mysql -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.13</version>
        </dependency>
        <!-- jpa -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>


3 修改脚本

  1. 任意位置右键 Scripted Extensions -> Go To Scripts Directory

    image-20200713174938015

    1. 打开GeneratePOJOS.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
      
      /*
       * Available context bindings:
       *   SELECTION   Iterable<DasObject>
       *   PROJECT     project
       *   FILES       files helper
       */
      //修改为你的实体类的包名
      packageName = "com.apt.entity;"
      typeMapping = [
              (~/(?i)int/)                      : "Long",
              (~/(?i)float|double|decimal|real/): "Double",
              (~/(?i)bool|boolean/)             : "Boolean",
              (~/(?i)datetime|timestamp/)       : "java.util.Date",
              (~/(?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 "import lombok.Data;"
          out.println ""
          out.println "import javax.persistence.*;"
          out.println "import java.io.Serializable;"
          out.println "import com.fasterxml.jackson.annotation.JsonIgnoreProperties;"
          out.println ""
          out.println "@Data"
          out.println "@Entity"
          out.println "@Table(name = \"$tableName\")"
          out.println "@JsonIgnoreProperties({\"handler\", \"hibernateLazyInitializer\"})"
          out.println "public class $className  implements Serializable {"
          out.println ""
          out.println "    private static final long serialVersionUID = 1L;"
      
          // 判断自增
          if ((tableName + "_id").equalsIgnoreCase(fields[0].colum) || "id".equalsIgnoreCase(fields[0].colum)) {
              out.println "\t@Id"
              out.println "\t@GeneratedValue(strategy=GenerationType.IDENTITY)"
          }
          fields.each() {
              if (it.annos != "") out.println "  ${it.annos}"
              if (it.colum != it.name) {
                  out.println "\t@Column(name = \"${it.colum}\")"
              }
              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
              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]
      }
      
         3. 选择你要生成的表 可用按shift多选 也可以按ctrl选中某几个 然后 Scripted Extensions -> GeneratePojos.groovy
      

      image-20200713175518269

      1. 弹出的文件框中选中生成位置

        image-20200713175635081

        1. 生成代码

          image-20200713175821151

0

评论区