使用idea自动生成jpa的三层架构

3 篇文章 0 订阅

1.连接idea自带的database
2.选择好数据库,右键

在这里插入图片描述
选择下面的Go to Scripts Directory

找到文件 Generate POJOs.groovy
在这里插入图片描述

3.修改文件内容

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

import java.text.SimpleDateFormat

config = [
        impSerializable  : true,
        extendBaseEntity : false,
        extendBaseService: false,
        useLombok        : true, // 不使用会生成get、set方法

        // 不生成哪个就注释哪个
        generateItem     : [
                "Entity",
                "Service",
                "Controller",//第一步
                "Repository",
//                "RepositoryCustom",
//                "RepositoryImpl",
                "ServiceImpl",
        ]
]

baseEntityPackage = "com.dz.demo.framework.base.BaseEntity"
baseServicePackage = "com.dz.demo.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)
  }
}

// 生成对应的文件              开始起飞
def generate(table, dir) {

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

  mkdirs([entityPath, servicePath, repPath, serviceImplPath, controllerPath])

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

  if (isGenerate("Entity")) {
    genUTF8File(entityPath, "${entityName}.java").withPrintWriter { out -> genEntity(out, table, entityName, fields, basePackage) }
  }
  if (isGenerate("Service")) {
    genUTF8File(servicePath, "${entityName}Service.java").withPrintWriter { out -> genService(out, table, entityName, fields, basePackage) }
  }
  //第二步 记得改后面的方法
  if (isGenerate("Controller")) {
    genUTF8File(controllerPath, "${entityName}Controller.java").withPrintWriter { out -> genController(out, table, entityName, fields, basePackage) }
  }
  if (isGenerate("Repository")) {
    genUTF8File(repPath, "${entityName}Repository.java").withPrintWriter { out -> genRepository(out, table, entityName, fields, basePackage) }
  }
  if (isGenerate("RepositoryCustom")) {
    genUTF8File(repPath, "${entityName}RepositoryCustom.java").withPrintWriter { out -> genRepositoryCustom(out, entityName, basePackage) }
  }
  if (isGenerate("RepositoryImpl")) {
    genUTF8File(repImpPath, "${entityName}RepositoryImpl.java").withPrintWriter { out -> genRepositoryImpl(out, table, entityName, fields, basePackage) }
  }
  if (isGenerate("ServiceImpl")) {
    genUTF8File(serviceImplPath, "${entityName}ServiceImpl.java").withPrintWriter { out -> genServiceImpl(out, table, entityName, fields, basePackage) }
  }

}

// 判断是否需要被生成
def isGenerate(itemName) {
  config.generateItem.contains(itemName)
}

// 首字母小写转换
def theFirstToLowerCase(str) {
  StringBuilder sb = new StringBuilder();
  sb.append(str.substring(0, 1).toLowerCase())
  sb.append(str.substring(1))

  return sb.toString();
}

// 指定文件编码方式,防止中文注释乱码
def genUTF8File(dir, fileName) {
  new PrintWriter(new OutputStreamWriter(new FileOutputStream(new File(dir, fileName)), "utf-8"))
}

// 生成每个字段
def genProperty(out, field) {

  out.println ""
  out.println "\t/**"
  out.println "\t * ${field.comment.toString()}"
//  out.println "\t * default value: ${field.default}"
  out.println "\t */"
  // 默认表的第一个字段为主键
  if (field.position == 1) {
    out.println "\t@Id"
    //自增主键需要
    out.println "\t@GeneratedValue(strategy = GenerationType.IDENTITY)"
  }
  // 枚举不需要长度
//  out.println "\t@Column(name = \"${field.colum}\", nullable = ${!field.isNotNull}${field.dataType == "enum" ? "" : ", length = $field.len"})"
  out.println "\t@Column(name = \"${field.colum}\", nullable = ${!field.isNotNull}${field.dataType == "enum" ? "" : ""})"
  out.println "\tprivate ${field.type} ${field.name};"
}

// 生成get、get方法
def genGetSet(out, field) {

  // get
  out.println "\t"
  out.println "\tpublic ${field.type} get${field.name.substring(0, 1).toUpperCase()}${field.name.substring(1)}() {"
  out.println "\t\treturn this.${field.name};"
  out.println "\t}"

  // set
  out.println "\t"
  out.println "\tpublic void set${field.name.substring(0, 1).toUpperCase()}${field.name.substring(1)}(${field.type} ${field.name}) {"
  out.println "\t\tthis.${field.name} = ${field.name};"
  out.println "\t}"
}

// 生成实体类
def genEntity(out, table, entityName, fields, basePackage) {
  out.println "package ${basePackage}.entity;"
  out.println ""
  if (config.extendBaseEntity) {
//    out.println "import $baseEntityPackage;"
  }
  if (config.useLombok) {
    out.println "import lombok.Data;"
  }
  if (config.impSerializable) {
    out.println "import java.io.Serializable;"
  }
  out.println "import javax.persistence.*;"
  out.println ""
  out.println "/**\n" +
          " * @Description  \n" +
          " * @Author  xwd\n" + //1. 修改idea为自己名字
          " * @Date " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " \n" +
          " */"
  if (config.useLombok) {
    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" : ""} {"

  if (config.extendBaseEntity) {
    fields = fields.findAll { it ->
      !baseEntityProperties.any { it1 -> it1 == it.name }
    }
  }

  fields.each() {
    genProperty(out, it)
  }

  if (!config.useLombok) {
    fields.each() {
      genGetSet(out, it)
    }
  }
  out.println "}"
}

// 生成Service
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 "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 repository;"
  out.println "}"
}

// 生成Controller 第三步
def genController(out, table, entityName, fields, basePackage) {
  out.println "package ${basePackage}.controller;"
  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 lombok.extern.slf4j.Slf4j;"
  out.println "import org.springframework.web.bind.annotation.RequestMapping;"
  out.println "import org.springframework.web.bind.annotation.RestController;"
  out.println "import ${basePackage}.service.${entityName}Service;"
  out.println "import javax.annotation.Resource;"
  out.println ""
  out.println "@Slf4j"
  out.println "@RestController"
  out.println "@RequestMapping(\"/${entityName.substring(0,1).toLowerCase()}${entityName.substring(1)}\")"//首字母小写
  out.println "public class ${entityName}Controller${config.extendBaseService ? " extends BaseService<$entityName, ${fields[0].type}>" : ""}  {"
  out.println ""
  out.println "\t@Resource"
  out.println "\tprivate ${entityName}Service "+theFirstToLowerCase("${entityName}")+"Service;"
  out.println "}"
}

// 生成Repository
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 "import org.springframework.data.jpa.repository.JpaSpecificationExecutor;"
  out.println ""
  out.println "public interface ${entityName}Repository extends JpaRepository<$entityName, ${fields[0].type}>, JpaSpecificationExecutor<$entityName>{"
  out.println ""
  out.println "}"
}

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

// 生成RepositoryImpl
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 "}"
}
// 生成ServiceImpl
def genServiceImpl(out, table, entityName, fields, basePackage) {
  out.println "package ${basePackage}.service.impl;"
  out.println ""
  out.println "import ${basePackage}.service.${entityName}Service;"
  out.println "import ${basePackage}.repository.${entityName}Repository;"
  out.println "import javax.annotation.Resource;"
//  out.println "import ${basePackage}.repository.${entityName}RepositoryCustom;"
  out.println "import org.springframework.stereotype.Service;"
  out.println ""
//  out.println "import javax.persistence.EntityManager;"
//  out.println "import javax.persistence.PersistenceContext;"
  out.println ""
  out.println "@Service"
  out.println "public class ${entityName}ServiceImpl implements ${entityName}Service {"
  out.println ""
  out.println "\t@Resource"
  out.println "\tprivate ${entityName}Repository repository;"
//  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,
                       dataType : col.getDataType().toString().replaceAll(/\(.*\)/, "").toLowerCase(),
                       len      : col.getDataType().toString().replaceAll(/[^\d]/, ""),
                       default  : col.getDefault(),
                       comment  : col.getComment(),
                       isNotNull: col.isNotNull(),
                       position : col.getPosition(),
//                           getDefault            : col.getDefault(),
//                           getParent             : col.getParent(),
//                           getTable              : col.getTable(),
//                           getDataType           : col.getDataType(),
//                           isNotNull             : col.isNotNull(),
//                           getWeight             : col.getWeight(),
//                           getDocumentation      : col.getDocumentation(),
//                           getTableName          : col.getTableName(),
//                           getName               : col.getName(),
//                           getLanguage           : col.getLanguage(),
//                           getTypeName           : col.getTypeName(),
//                           isDirectory           : col.isDirectory(),
//                           isValid               : col.isValid(),
//                           getComment            : col.getComment(),
//                           getText               : col.getText(),
//                           getDeclaration        : col.getDeclaration(),
//                           getPosition           : col.getPosition(),
//                           canNavigate           : col.canNavigate(),
//                           isWritable            : col.isWritable(),
//                           getIcon               : col.getIcon(),
//                           getManager            : col.getManager(),
//                           getDelegate           : col.getDelegate(),
//                           getChildren           : col.getChildren(),
//                           getKind               : col.getKind(),
//                           isCaseSensitive       : col.isCaseSensitive(),
//                           getProject            : col.getProject(),
//                           getDataSource         : col.getDataSource(),
//                           getVirtualFile        : col.getVirtualFile(),
//                           getMetaData           : col.getMetaData(),
//                           canNavigateToSource   : col.canNavigateToSource(),
//                           getDisplayOrder       : col.getDisplayOrder(),
//                           getDasParent          : col.getDasParent(),
//                           getLocationString     : col.getLocationString(),
//                           getDependences        : col.getDependences(),
//                           getBaseIcon           : col.getBaseIcon(),
//                           getNode               : col.getNode(),
//                           getTextLength         : col.getTextLength(),
//                           getFirstChild         : col.getFirstChild(),
//                           getLastChild          : col.getLastChild(),
//                           getNextSibling        : col.getNextSibling(),
//                           getTextOffset         : col.getTextOffset(),
//                           getPrevSibling        : col.getPrevSibling(),
//                           getPresentation       : col.getPresentation(),
//                           isPhysical            : col.isPhysical(),
//                           getTextRange          : col.getTextRange(),
//                           getPresentableText    : col.getPresentableText(),
//                           textToCharArray       : col.textToCharArray(),
//                           getStartOffsetInParent: col.getStartOffsetInParent(),
//                           getContext            : col.getContext(),
//                           getUseScope           : col.getUseScope(),
//                           getResolveScope       : col.getResolveScope(),
//                           getReferences         : col.getReferences(),
//                           getReference          : col.getReference(),
//                           getContainingFile     : col.getContainingFile(),
//                           getOriginalElement    : col.getOriginalElement(),
//                           getNavigationElement  : col.getNavigationElement(),
//                           getUserDataString     : col.getUserDataString(),
//                           isUserDataEmpty       : col.isUserDataEmpty(),
//                           getDbParent           : col.getDbParent(),
               ]]

  }
}

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

然后点击 运行即可

在这里插入图片描述

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
使用Spring Boot和JPA的情况下,可以按照以下步骤进行配置和使用: 1. 首先,在你的项目中添加Spring Boot和JPA的依赖。可以在项目的pom.xml文件中添加以下依赖项: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> ``` 2. 创建一个实体类,用于映射数据库表。在你的代码中,可以看到一个名为User的实体类\[1\]。这个实体类使用JPA的注解来定义表名、字段和关联关系等。 3. 创建一个DAO接口,用于操作数据库。在你的代码中,可以看到一个名为UserDao的接口\[2\],它继承了JpaRepository接口,并指定了实体类和主键类型。 4. 创建一个Service接口和实现类,用于处理业务逻辑。在你的代码中,可以看到一个名为IUserService的接口和一个名为UserService的实现类。在实现类中,可以注入UserDao,并在方法中调用UserDao的方法来操作数据库。 5. 创建一个Controller类,用于处理HTTP请求。在你的代码中,可以看到一个名为UserController的类\[3\],它使用了@RestController注解来标识这是一个控制器类,并使用@RequestMapping注解来指定请求路径。在方法中,可以注入IUserService,并调用其方法来处理请求。 6. 最后,你可以使用IDEA来运行你的应用程序,并通过访问http://localhost:8080/user/queryAll来测试你的接口。 总结起来,使用Spring Boot和JPA可以方便地进行数据库操作。你需要创建实体类、DAO接口、Service接口和实现类以及Controller类来完成整个流程。通过注解和依赖注入,你可以简化代码并提高开发效率。 #### 引用[.reference_title] - *1* *2* *3* [idea 搭建 springboot+jpa](https://blog.csdn.net/Baldprogrammer/article/details/103275398)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

卧虎3

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值