User-Profile-Image
hankin
  • 5
  • Java
  • Kotlin
  • Spring
  • Web
  • SQL
  • MegaData
  • More
  • Experience
  • Enamiĝu al vi
  • 分类
    • Zuul
    • Zookeeper
    • XML
    • WebSocket
    • Web Notes
    • Web
    • Vue
    • Thymeleaf
    • SQL Server
    • SQL Notes
    • SQL
    • SpringSecurity
    • SpringMVC
    • SpringJPA
    • SpringCloud
    • SpringBoot
    • Spring Notes
    • Spring
    • Servlet
    • Ribbon
    • Redis
    • RabbitMQ
    • Python
    • PostgreSQL
    • OAuth2
    • NOSQL
    • Netty
    • MySQL
    • MyBatis
    • More
    • MinIO
    • MegaData
    • Maven
    • LoadBalancer
    • Kotlin Notes
    • Kotlin
    • Kafka
    • jQuery
    • JavaScript
    • Java Notes
    • Java
    • Hystrix
    • Git
    • Gateway
    • Freemarker
    • Feign
    • Eureka
    • ElasticSearch
    • Docker
    • Consul
    • Ajax
    • ActiveMQ
  • 页面
    • 归档
    • 摘要
    • 杂图
    • 问题随笔
  • 友链
    • Spring Cloud Alibaba
    • Spring Cloud Alibaba - 指南
    • Spring Cloud
    • Nacos
    • Docker
    • ElasticSearch
    • Kotlin中文版
    • Kotlin易百
    • KotlinWeb3
    • KotlinNhooo
    • 前端开源搜索
    • Ktorm ORM
    • Ktorm-KSP
    • Ebean ORM
    • Maven
    • 江南一点雨
    • 江南国际站
    • 设计模式
    • 熊猫大佬
    • java学习
    • kotlin函数查询
    • Istio 服务网格
    • istio
    • Ktor 异步 Web 框架
    • PostGis
    • kuangstudy
    • 源码地图
    • it教程吧
    • Arthas-JVM调优
    • Electron
    • bugstack虫洞栈
    • github大佬宝典
    • Sa-Token
    • 前端技术胖
    • bennyhuo-Kt大佬
    • Rickiyang博客
    • 李大辉大佬博客
    • KOIN
    • SQLDelight
    • Exposed-Kt-ORM
    • Javalin—Web 框架
    • http4k—HTTP包
    • 爱威尔大佬
    • 小土豆
    • 小胖哥安全框架
    • 负雪明烛刷题
    • Kotlin-FP-Arrow
    • Lua参考手册
    • 美团文章
    • Java 全栈知识体系
    • 尼恩架构师学习
    • 现代 JavaScript 教程
    • GO相关文档
    • Go学习导航
    • GoCN社区
    • GO极客兔兔-案例
    • 讯飞星火GPT
    • Hollis博客
    • PostgreSQL德哥
    • 优质博客推荐
    • 半兽人大佬
    • 系列教程
    • PostgreSQL文章
    • 云原生资料库
    • 并发博客大佬
Help?

Please contact us on our email for need any support

Support
    首页   ›   Kotlin   ›   Kotlin Notes   ›   正文
Kotlin Notes

Mybatis-plus—kotlin代码生成

2020-11-10 11:55:43
2138  0 1
参考目录 隐藏
1) [v2.1.5] 2017.11.11
2) 关键:
3) 代码示例:
4) GeneratorFactory.kt
5) 自定义模板
6) entity.kt.ftl
7) mapper.java.ftl

阅读完需:约 4 分钟

mybatis-plus 2.1.5 发布,新增 kotlin 代码生成

[v2.1.5] 2017.11.11

  • 通用枚举 spring boot 兼容调整
  • PostgreSQL 支持关键词非关键词转换问题
  • Cat73 PR 稍微调整下自动生成的代码
  • 支持 kotlin 代码生成
  • bugfix for metaObj handler set val which not included in …
  • alibaba 规范调整
  • 其他

能自动生成代码就很舒服。

关键:

Mybatis-plus关键点:

代码示例:

GeneratorFactory.kt

package com.example.kotlin01

import com.baomidou.mybatisplus.annotation.DbType
import com.baomidou.mybatisplus.annotation.IdType
import com.baomidou.mybatisplus.core.toolkit.StringPool
import com.baomidou.mybatisplus.generator.AutoGenerator
import com.baomidou.mybatisplus.generator.InjectionConfig
import com.baomidou.mybatisplus.generator.config.*
import com.baomidou.mybatisplus.generator.config.po.TableInfo
import com.baomidou.mybatisplus.generator.config.rules.DateType
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine
import java.util.*


/**
 * @Author: xjh
 * @param null
 * @return null
 * @Description:
 * @Date: 11:46 2020/11/10
 * @version 1.0
 */
    fun main(args: Array<String>) {
        generator()
    }

    fun generator(){
        println("begin generating")
        val projectPath = System.getProperty("user.dir")

        var mpg = AutoGenerator()

        var globalConfig = GlobalConfig()
        globalConfig.isKotlin = true
        globalConfig.author = "xjh"
        globalConfig.isOpen = false
        globalConfig.outputDir = System.getProperty("user.dir") + "/src/main/kotlin"
        globalConfig.isFileOverride = true
        globalConfig.idType = IdType.AUTO
        globalConfig.xmlName = "%sMapper"
        globalConfig.mapperName = "%sMapper"
        globalConfig.serviceName="%sService"
        globalConfig.serviceImplName = "%sServiceImpl"
        globalConfig.controllerName = "%sController"
        globalConfig.isBaseColumnList = true
        globalConfig.isBaseResultMap = true
        globalConfig.dateType= DateType.ONLY_DATE

        mpg.globalConfig = globalConfig

        var dsc = DataSourceConfig()
        dsc.dbType = DbType.POSTGRE_SQL
        dsc.driverName = "org.postgresql.Driver"
        dsc.url = "jdbc:postgresql://10.4.2.6:15432/smartpark?useSSL=false&serverTimezone=Asia/Shanghai&characterEncoding=utf8"
        dsc.username = "liantu"
        dsc.password = "liantu123456"
        dsc.schemaName = "vehicle"

        mpg.dataSource = dsc


        // 包配置
        var pc = PackageConfig();
//	        pc.setModuleName(scanner("模块名"));
        pc.parent="com.example.kotlin01.kotlinns"
        mpg.packageInfo=pc

        // 自定义配置
        val cfg: InjectionConfig = object : InjectionConfig() {
            override fun initMap() {
                // to do nothing
            }
        }
        val focList: MutableList<FileOutConfig> = ArrayList()
        focList.add(object : FileOutConfig("/templates/mapper.xml.ftl") {
            override fun outputFile(tableInfo: TableInfo): String? {
                // 自定义输入文件名称
                return (projectPath.toString() + "/src/main/resources/mapper/"
                        + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML)
            }
        })

        // config xml template and outpath
        cfg.fileOutConfigList = focList
        mpg.cfg = cfg

        val tc = TemplateConfig()
        tc.entityKt="/templates/entity.kt"
        tc.mapper="/templates/mapper.java"
        mpg.template=tc

        var strategy=StrategyConfig()
        strategy.naming= NamingStrategy.underline_to_camel
        strategy.columnNaming=NamingStrategy.underline_to_camel
        strategy.isRestControllerStyle=true
        strategy.isControllerMappingHyphenStyle=true
        var sum=StringBuffer()
        sum.append(pc.moduleName).append("_")
        strategy.setTablePrefix(sum.toString())


        mpg.strategy = strategy


        mpg.templateEngine = FreemarkerTemplateEngine()
        mpg.execute();
    }

自定义模板

自定义模板可以找官方的来修改!

entity.kt.ftl

package ${package.Entity}

<#list table.importPackages as pkg>
import ${pkg}
</#list>
import com.baomidou.mybatisplus.annotation.*
<#if swagger2>
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
</#if>
/**
 * <p>
 * ${table.comment}
 * </p>
 *
 * @author ${author}
 * @since ${date}
 */
@TableName("${table.name}")
<#if swagger2>
@ApiModel(value="${entity}对象", description="${table.comment!}")
</#if>
<#if superEntityClass??>
class ${entity} : ${superEntityClass}<#if activeRecord><${entity}></#if> {
<#elseif activeRecord>
class ${entity} : Model<${entity}>() {
<#else>
class ${entity} : Serializable {
</#if>

<#-- ----------  BEGIN 字段循环遍历  ---------->
<#list table.fields as field>
<#if field.keyFlag>
    <#assign keyPropertyName="${field.propertyName}"/>
</#if>

<#if field.comment!?length gt 0>
<#if swagger2>
        @ApiModelProperty(value = "${field.comment}")
<#else>
    /**
     * ${field.comment}
     */
</#if>
</#if>
<#if field.keyFlag>
<#-- 主键 -->
<#if field.keyIdentityFlag>
    @TableId(value = "${field.annotationColumnName}", type = IdType.AUTO)
<#elseif idType ??>
    @TableId(value = "${field.annotationColumnName}", type = IdType.${idType})
<#elseif field.convert>
    @TableId("${field.annotationColumnName}")
</#if>
<#-- 普通字段 -->
<#elseif field.fill??>
<#-- -----   存在字段填充设置   ----->
<#if field.convert>
    @TableField(value = "${field.annotationColumnName}", fill = FieldFill.${field.fill})
<#else>
    @TableField(fill = FieldFill.${field.fill})
</#if>
<#elseif field.convert>
    @TableField("${field.annotationColumnName}")
</#if>
<#-- 乐观锁注解 -->
<#if (versionFieldName!"") == field.name>
    @Version
</#if>
<#-- 逻辑删除注解 -->
<#if (logicDeleteFieldName!"") == field.name>
    @TableLogic
</#if>
    <#if field.propertyType == "Integer">
    var ${field.propertyName}: Int? = null
    <#else>
    var ${field.propertyName}: ${field.propertyType}? = null
    </#if>
</#list>
<#-- ----------  END 字段循环遍历  ---------->


<#if entityColumnConstant>
    companion object {
<#list table.fields as field>

        const val ${field.name?upper_case} : String = "${field.name}"

</#list>
    }

</#if>
<#if activeRecord>
    override fun pkVal(): Serializable? {
<#if keyPropertyName??>
        return ${keyPropertyName}
<#else>
        return null
</#if>
    }

</#if>
    override fun toString(): String {
        return "${entity}{" +
<#list table.fields as field>
<#if field_index==0>
        "${field.propertyName}=" + ${field.propertyName} +
<#else>
        ", ${field.propertyName}=" + ${field.propertyName} +
</#if>
</#list>
        "}"
    }
}

mapper.java.ftl

package ${package.Mapper};

import ${package.Entity}.${entity};
import ${superMapperClassPackage};
import org.apache.ibatis.annotations.Mapper

/**
 * <p>
 * ${table.comment!} Mapper 接口
 * </p>
 *
 * @author ${author}
 * @since ${date}
 */
@Mapper
<#if kotlin>
interface ${table.mapperName} : ${superMapperClass}<${entity}>
<#else>
public interface ${table.mapperName} extends ${superMapperClass}<${entity}> {

}
</#if>

如本文“对您有用”,欢迎随意打赏作者,让我们坚持创作!

1 打赏
Enamiĝu al vi
不要为明天忧虑.因为明天自有明天的忧虑.一天的难处一天当就够了。
543文章 68评论 294点赞 594295浏览

随机文章
Spring笔记12—使用xml配置AOP
5年前
SpringSecurity—OAuth 2(四)密码模式
5年前
SpringBoot—中实现定时任务的两种方式 + 异步任务
5年前
MyBatisPlus—分页查询以及自定义sql分页
5年前
实用网站(待)
5年前
博客统计
  • 日志总数:543 篇
  • 评论数目:68 条
  • 建站日期:2020-03-06
  • 运行天数:1927 天
  • 标签总数:23 个
  • 最后更新:2024-12-20
Copyright © 2025 网站备案号: 浙ICP备20017730号 身体没有灵魂是死的,信心没有行为也是死的。
主页
页面
  • 归档
  • 摘要
  • 杂图
  • 问题随笔
博主
Enamiĝu al vi
Enamiĝu al vi 管理员
To be, or not to be
543 文章 68 评论 594295 浏览
测试
测试
看板娘
赞赏作者

请通过微信、支付宝 APP 扫一扫

感谢您对作者的支持!

 支付宝 微信支付