1. 通过数据库动态生成自己想要生成的各种模板,需要了解grovery。

  2. view -> Tool Windows -> Database

  1. + -> Data source -> MySQL

  2. 配置数据库信息

  3. 建立存放实体的包

  4. 导入必要maven依赖

  <!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.21</version>
</dependency>
<!--jpa-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
  1. 在database视图区域任意地方右键,然后Scripted Extensions -> Go to Scripts Directory

  2. 复制下面的文件到6中跳转的文件夹中

  • 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 config = [
    impSerializable : true,
    extendBaseEntity : false,
    extendBaseService: true ]
    baseEntityPackage = "com.hhsj.base.BaseEntity"
    baseServicePackage = "com.hhsj.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",
    serviceImpPath = "${dir.toString()}\\service\\impl" mkdirs([entityPath, servicePath, repPath, serviceImpPath]) 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("${serviceImpPath}\\${entityName}ServiceImpl.java").withPrintWriter { out -> getServiceImpl(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 "import com.fasterxml.jackson.annotation.JsonIgnoreProperties;"
    out.println ""
    }
    out.println "import javax.persistence.*;"
    out.println ""
    out.println "@Data"
    out.println "@Entity"
    out.println "@Table(name = \"${table.getName()}\")"
    out.println "@JsonIgnoreProperties(value={\"hibernateLazyInitializer\",\"handler\",\"fieldHandler\"})"
    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"
    out.println "\t@GeneratedValue(strategy = GenerationType.IDENTITY)"
    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;"
    out.println "import ${basePackage}.base.Result;"
    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 "public interface ${entityName}Service${config.extendBaseService ? " extends BaseService<$entityName, ${fields[0].type}>" : ""} {"
    out.println ""
    out.println " //根据id查询"
    out.println " public Result getOne(${fields[0].type} id);"
    out.println ""
    out.println " //根据id删除"
    out.println " public Result deleteOne(${fields[0].type} id);"
    out.println ""
    out.println " //根据id保存"
    out.println " public Result saveOne(${entityName} entity);"
    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}>{}"
    } /*def genRepositoryCustom(out, entityName, basePackage) {
    out.println "package ${basePackage}.repository;"
    out.println ""
    out.println "public interface ${entityName}RepositoryCustom { "
    out.println "}"
    }*/ def getServiceImpl(out, table, entityName, fields, basePackage) {
    out.println "package ${basePackage}.service.impl;"
    out.println ""
    out.println "import ${basePackage}.service.${entityName}Service;"
    out.println "import org.springframework.stereotype.Service;"
    out.println "import ${basePackage}.base.Result;"
    out.println "import ${basePackage}.entity.${entityName};"
    out.println "import ${basePackage}.service.${entityName}Service;"
    out.println "import ${basePackage}.repository.${entityName}Repository;"
    out.println "import org.springframework.beans.factory.annotation.Autowired;"
    out.println ""
    out.println "@Service"
    out.println "public class ${entityName}ServiceImpl implements ${entityName}Service {"
    out.println ""
    out.println "\t@Autowired"
    out.println "\tprivate ${entityName}Repository rep;"
    out.println ""
    out.println "\t@Override"
    out.println "\tpublic Result getOne(${fields[0].type} id){"
    out.println " \t\t${entityName} one = rep.getOne(id);"
    out.println "\t\treturn Result.builder().success().data(one).build();"
    out.println "\t}"
    out.println ""
    out.println "\t@Override"
    out.println "\tpublic Result deleteOne(${fields[0].type} id){"
    out.println " \t\trep.deleteById(id);"
    out.println "\t\treturn Result.builder().success().build();"
    out.println "\t}"
    out.println ""
    out.println "\t@Override"
    out.println "\tpublic Result saveOne(${entityName} entity){"
    out.println " \t\t${entityName} one = rep.save(entity);"
    out.println "\t\treturn Result.builder().success().data(one).build();"
    out.println "\t}"
    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]
    }

    生成模板



spring data jpa 代码生成!!(精华帖)的更多相关文章

  1. Spring data jpa 使用技巧记录

    软件152 尹以操 最近在用Springboot 以及Spring data jpa  ,使用jpa可以让我更方便的操作数据库,特开此帖记录使用jpa的一些小技巧. 一.使用spring data j ...

  2. Spring Data Jpa:分页、Specification、Criteria

    分页的主要接口与类 PagingAndSortingRepository 继承自 CrudRepository 接口,提供了排序以及分页查询能力,提供了两个方法 Iterable<T> f ...

  3. Spring Data JPA系列5:让IDEA自动帮你写JPA实体定义代码

    大家好,又见面了. 这是本系列的最后一篇文档啦,先来回顾下前面4篇: 在第1篇<Spring Data JPA系列1:JDBC.ORM.JPA.Spring Data JPA,傻傻分不清楚?给你 ...

  4. 快速搭建springmvc+spring data jpa工程

    一.前言 这里简单讲述一下如何快速使用springmvc和spring data jpa搭建后台开发工程,并提供了一个简单的demo作为参考. 二.创建maven工程 http://www.cnblo ...

  5. spring boot(五):spring data jpa的使用

    在上篇文章springboot(二):web综合开发中简单介绍了一下spring data jpa的基础性使用,这篇文章将更加全面的介绍spring data jpa 常见用法以及注意事项 使用spr ...

  6. 转:使用 Spring Data JPA 简化 JPA 开发

    从一个简单的 JPA 示例开始 本文主要讲述 Spring Data JPA,但是为了不至于给 JPA 和 Spring 的初学者造成较大的学习曲线,我们首先从 JPA 开始,简单介绍一个 JPA 示 ...

  7. 深入浅出学Spring Data JPA

    第一章:Spring Data JPA入门 Spring Data是什么 Spring Data是一个用于简化数据库访问,并支持云服务的开源框架.其主要目标是使得对数据的访问变得方便快捷,并支持map ...

  8. spring data jpa 调用存储过程

    网上这方面的例子不是很多,研究了一下,列出几个调用的方法. 假如我们有一个mysql的存储过程 CREATE DEFINER=`root`@`localhost` PROCEDURE `plus1in ...

  9. Spring Data JPA 学习记录1 -- 单向1:N关联的一些问题

    开新坑 开新坑了(笑)....公司项目使用的是Spring Data JPA做持久化框架....学习了一段时间以后发现了一点值得注意的小问题.....与大家分享 主要是针对1:N单向关联产生的一系列问 ...

随机推荐

  1. java 基本语法(十五)Lambda (二)函数式接口

    1.函数式接口的使用说明> 如果一个接口中,只声明了一个抽象方法,则此接口就称为函数式接口.> 我们可以在一个接口上使用 @FunctionalInterface 注解,这样做可以检查它是 ...

  2. C#-性能-二维数组和数组的数组的性能比较

    两者是3:2的消耗比例 const int NUM = 10000; int[,] vec = new int[NUM, NUM]; Stopwatch sw = Stopwatch.StartNew ...

  3. 008.Nginx静态资源

    一 Nginx静态资源概述 1.1 静态资源类型 Nginx作为静态资源Web服务器部署配置, 传输非常高效, 常常用于静态资源处理,请求以及动静分离.通常非服务器动态运行生成的文件属于静态资源. 类 ...

  4. spring boot实现简单的登录拦截

    一.思路 1.在pom.xml导入相关包 2.先写个简单的认证适配器(WebSecurityConfig extends WebSecurityConfigurerAdapter),登录拦截后就会跳转 ...

  5. 关于JS深拷贝和浅拷贝

    最近在前端开发中遇到一些问题,就是数组中的某个对象或某个对象的值改变之后,在不刷新页面的时候需要重新渲染值时,页面显示的还是原来的数据.比如: data{ A:[{id:1,num:1},{id:2, ...

  6. mysql间隙锁

    什么是间隙锁(gap lock)? 间隙锁是一个在索引记录之间的间隙上的锁. 间隙锁的作用? 保证某个间隙内的数据在锁定情况下不会发生任何变化.比如我mysql默认隔离级别下的可重复读(RR). 当使 ...

  7. 读取文件夹内容解析为Tree结构

    package com.mine.io; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import ...

  8. 【week1错题集】

    day9[2.f] # day9 题2.f ''' 有如下文件,t1.txt,里面的内容为: 葫芦娃,葫芦娃, 一根藤上七个瓜 风吹雨打,都不怕, 啦啦啦啦. 以r模式打开文件,从‘风吹雨打..... ...

  9. xmake从入门到精通12:通过自定义脚本实现更灵活地配置

    xmake是一个基于Lua的轻量级现代化c/c++的项目构建工具,主要特点是:语法简单易上手,提供更加可读的项目维护,实现跨平台行为一致的构建体验. 本文主要详细讲解下,如何通过添加自定义的脚本,在脚 ...

  10. nginx 日志功能详解

    nginx 日志功能 在 nginx 中有两种日志: access_log:访问日志,通过访问日志可以获取用户的IP.请求处理的时间.浏览器信息等 error_log:错误日志,记录了访问出错的信息, ...