Spring Boot JPA idea代码自动生成 其二

之前说过怎么生成,可以参考这里当时拿出一个实体类的生成。最近有把生成的groovy代码改造了一番,现在可以一键生成entityservicerepository类了。

我们现有的entityservice都是有基类可以选择继承的,主要看看entity的基类BaseEntity

@Data
@MappedSuperclass
@EntityListeners({AuditingEntityListener.class})
public class BaseEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", nullable = false, length = 22, unique = true)
    protected Long id;

    @CreatedDate
    @Column(name = "create_date", nullable = false)
    protected Date createDate;

    @LastModifiedDate
    @Column(name = "last_modified_date")
    protected Date lastModifiedDate;

    @Version
    @Column(name = "version", nullable = false)
    protected Integer version;
}

@Datalombok的注解,用于自动生成getset方法,使用lombok需要在添加maven依赖

<!-- lombok -->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>

再看看生成好的文件目录结构

image.png

我们的数据表:


image.png

很好这个表是需要继承基类生成的。

打开代码进行调整

import com.intellij.database.model.DasTable
import com.intellij.database.model.ObjectKind
import com.intellij.database.util.Case
import com.intellij.database.util.DasUtil

config = [
        impSerializable  : true,
        extendBaseEntity : true,
        extendBaseService: true

]
baseEntityPackage = "com.yija.project.framework.base.BaseEntity"
baseServicePackage = "com.yija.project.framework.base.BaseService"
baseEntityProperties = ["id", "createDate", "lastModifiedDate", "version"]
typeMapping = [
        (~/(?i)bool|boolean|tinyint/)     : "Boolean",
        (~/(?i)bigint/)                   : "Long",
        (~/int/)                          : "Integer",
        (~/(?i)float|double|decimal|real/): "Double",
        (~/(?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)
    }
}
//dif -> E:\DEVELOPE\Code\jpademo\src\main\java\com\demo\jpa
def generate(table, dir) {

    def entityPath = "${dir.toString()}\\entity",
        servicePath = "${dir.toString()}\\service",
        repPath = "${dir.toString()}\\repository",
        repImpPath = "${dir.toString()}\\repository\\impl"

    mkdirs([entityPath, servicePath, repPath, repImpPath])

    def entityName = javaName(table.getName(), true)
    def fields = calcFields(table)
    def basePackage = clacBasePackage(dir)

    new File("${entityPath}\\${entityName}.java").withPrintWriter { out -> genEntity(out, table, entityName, fields, basePackage) }
    new File("${servicePath}\\${entityName}Service.java").withPrintWriter { out -> genService(out, table, entityName, fields, basePackage) }
    new File("${repPath}\\${entityName}Repository.java").withPrintWriter { out -> genRepository(out, table, entityName, fields, basePackage) }
    new File("${repPath}\\${entityName}RepositoryCustom.java").withPrintWriter { out -> genRepositoryCustom(out, entityName, basePackage) }
    new File("${repImpPath}\\${entityName}RepositoryImpl.java").withPrintWriter { out -> genRepositoryImpl(out, table, entityName, fields, basePackage) }

}

def genProperty(out, field) {
    if (field.annos != "") out.println "  ${field.annos}"
    if (field.colum != field.name) {
        out.println "\t@Column(name = \"${field.colum}\")"
    }
    out.println "\tprivate ${field.type} ${field.name};"
    out.println ""
}

def genEntity(out, table, entityName, fields, basePackage) {
    out.println "package ${basePackage}.entity;"
    out.println ""
    if (config.extendBaseEntity) {
        out.println "import $baseEntityPackage;"
    }
    out.println "import lombok.Data;"
    out.println ""
    if (config.impSerializable) {
        out.println "import java.io.Serializable;"
        out.println ""
    }
    out.println "import javax.persistence.*;"
    out.println ""
    out.println "@Data"
    out.println "@Entity"
    out.println "@Table(name = \"${table.getName()}\")"
    out.println "public class $entityName${config.extendBaseEntity ? " extends BaseEntity" : ""}${config.impSerializable ? " implements Serializable" : ""} {"
    out.println ""
    if (config.extendBaseEntity) {
        // 继承父类
        fields.each() { if (!isBaseEntityProperty(it.name)) genProperty(out, it) }
    } else {
        // 不继承父类
        out.println "\t@Id"
        fields.each() { genProperty(out, it) }
    }
    out.println "}"

}

def genService(out, table, entityName, fields, basePackage) {
    out.println "package ${basePackage}.service;"
    out.println ""
    out.println "import ${basePackage}.repository.${entityName}Repository;"
    if (config.extendBaseService) {
        out.println "import $baseServicePackage;"
        out.println "import ${basePackage}.entity.$entityName;"
    }
    out.println "import org.springframework.stereotype.Service;"
    out.println ""
    out.println "import javax.annotation.Resource;"
    out.println ""
    out.println "@Service"
    out.println "public class ${entityName}Service${config.extendBaseService ? " extends BaseService<$entityName, ${fields[0].type}>" : ""}  {"
    out.println ""
    out.println "\t@Resource"
    out.println "\tprivate ${entityName}Repository rep;"
    out.println "}"
}

def genRepository(out, table, entityName, fields, basePackage) {
    out.println "package ${basePackage}.repository;"
    out.println ""
    out.println "import ${basePackage}.entity.$entityName;"
    out.println "import org.springframework.data.jpa.repository.JpaRepository;"
    out.println ""
    out.println "public interface ${entityName}Repository extends JpaRepository<$entityName, ${fields[0].type}>, ${entityName}RepositoryCustom{}"
}

def genRepositoryCustom(out, entityName, basePackage) {
    out.println "package ${basePackage}.repository;"
    out.println ""
    out.println "public interface ${entityName}RepositoryCustom { "
    out.println "}"
}

def genRepositoryImpl(out, table, entityName, fields, basePackage) {
    out.println "package ${basePackage}.repository.impl;"
    out.println ""
    out.println "import ${basePackage}.repository.${entityName}RepositoryCustom;"
    out.println "import org.springframework.stereotype.Repository;"
    out.println ""
    out.println "import javax.persistence.EntityManager;"
    out.println "import javax.persistence.PersistenceContext;"
    out.println ""
    out.println "@Repository"
    out.println "public class ${entityName}RepositoryImpl implements ${entityName}RepositoryCustom {"
    out.println ""
    out.println "\t@PersistenceContext"
    out.println "\tprivate EntityManager em;"
    out.println "}"
}

def mkdirs(dirs) {
    dirs.forEach {
        def f = new File(it)
        if (!f.exists()) {
            f.mkdirs();
        }
    }
}

def clacBasePackage(dir) {
    dir.toString()
            .replaceAll("^.+\\\\src\\\\main\\\\java\\\\", "")
            .replaceAll("\\\\", ".")
}

def isBaseEntityProperty(property) {
    baseEntityProperties.find { it == property } != null
}
// 转换类型
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]
}

config中配置,需要使用entityservice的基类,实现Serializable接口,然后选择生成目录生成

image.png

看看生成好的类吧

  • Entity
package com.demo.jpa.entity;

import com.yija.project.framework.base.BaseEntity;
import lombok.Data;

import java.io.Serializable;

import javax.persistence.*;

@Data
@Entity
@Table(name = "game_history")
public class GameHistory extends BaseEntity implements Serializable {

   @Column(name = "user_id")
   private Long userId;

   private Integer score;
}
  • Service
package com.demo.jpa.service;

import com.demo.jpa.repository.GameHistoryRepository;
import com.yija.project.framework.base.BaseService;
import com.demo.jpa.entity.GameHistory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class GameHistoryService extends BaseService<GameHistory, Long>  {

    @Resource
    private GameHistoryRepository rep;
}
  • Repository
package com.demo.jpa.repository;

import com.demo.jpa.entity.GameHistory;
import org.springframework.data.jpa.repository.JpaRepository;

public interface GameHistoryRepository extends JpaRepository<GameHistory, Long>, GameHistoryRepositoryCustom{
}
  • RepositoryCustom
package com.demo.jpa.repository;

public interface GameHistoryRepositoryCustom { 
}

  • RepositoryImpl
package com.demo.jpa.repository.impl;

import com.demo.jpa.repository.GameHistoryRepositoryCustom;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

@Repository
public class GameHistoryRepositoryImpl implements GameHistoryRepositoryCustom {

    @PersistenceContext
    private EntityManager em;
}

Spring Boot JPA实体类idea自动生成 其三

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,736评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,167评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,442评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,902评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,302评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,573评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,847评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,562评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,260评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,531评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,021评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,367评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,016评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,068评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,827评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,610评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,514评论 2 269

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,099评论 18 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,358评论 6 343
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 170,566评论 25 707
  • 酝酿了那么多次的情绪 转瞬间极度升华 是心给了多少的电压 频繁而复杂 盛世中你毅力在哪层高塔 眼前的你犹如望不尽的...
    狒狒傻丫头_阅读 94评论 0 0
  • 正念练习:对觉知的正念 #40天身心成长计划# Day29: 正念练习:对觉知的正念 你关注了什么,你就会体验到什...
    悠悠然a阅读 155评论 0 0