当前位置:   article > 正文

Kotlin-集成SpringBoot+MyBatis+代码生成器_kotlin springboot

kotlin springboot

目录

一、相关版本

二、Maven因引入相关依赖

三、SpringBoot配置文件

四、代码生成工具

五、实现用户服务模块案例

1、Controller

2、Service

3、Entity

4、Mapper

5、接口测试


一、相关版本

工具版本
Idea2022.3.2
Springboot2.7.12
Kotlin1.8.20
MyBatis3.5.3.1
MySQL8.0.28
JDK1.8

相关代码已分享到Gitee:

https://gitee.com/Vmetrio/kotlin-springbooticon-default.png?t=N7T8https://gitee.com/Vmetrio/kotlin-springboot项目结构:

二、Maven因引入相关依赖

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <parent>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-parent</artifactId>
  8. <version>2.7.12</version>
  9. <relativePath/> <!-- lookup parent from repository -->
  10. </parent>
  11. <groupId>com.example</groupId>
  12. <artifactId>springboot</artifactId>
  13. <version>0.0.1-SNAPSHOT</version>
  14. <name>springboot</name>
  15. <description>springboot</description>
  16. <properties>
  17. <java.version>1.8</java.version>
  18. <kotlin.version>1.8.20</kotlin.version>
  19. </properties>
  20. <dependencies>
  21. <dependency>
  22. <groupId>org.springframework.boot</groupId>
  23. <artifactId>spring-boot-starter-web</artifactId>
  24. </dependency>
  25. <dependency>
  26. <groupId>com.fasterxml.jackson.module</groupId>
  27. <artifactId>jackson-module-kotlin</artifactId>
  28. </dependency>
  29. <dependency>
  30. <groupId>org.jetbrains.kotlin</groupId>
  31. <artifactId>kotlin-reflect</artifactId>
  32. </dependency>
  33. <dependency>
  34. <groupId>org.jetbrains.kotlin</groupId>
  35. <artifactId>kotlin-stdlib-jdk8</artifactId>
  36. </dependency>
  37. <dependency>
  38. <groupId>org.springframework.boot</groupId>
  39. <artifactId>spring-boot-starter-test</artifactId>
  40. <scope>test</scope>
  41. </dependency>
  42. <!--mysql-->
  43. <dependency>
  44. <groupId>com.mysql</groupId>
  45. <artifactId>mysql-connector-j</artifactId>
  46. </dependency>
  47. <!--mybatis-->
  48. <dependency>
  49. <groupId>com.baomidou</groupId>
  50. <artifactId>mybatis-plus-boot-starter</artifactId>
  51. <version>3.5.3.1</version>
  52. </dependency>
  53. <dependency>
  54. <groupId>com.baomidou</groupId>
  55. <artifactId>mybatis-plus-annotation</artifactId>
  56. <version>3.5.3.1</version>
  57. </dependency>
  58. <dependency>
  59. <groupId>com.baomidou</groupId>
  60. <artifactId>mybatis-plus-extension</artifactId>
  61. <version>3.5.3.1</version>
  62. </dependency>
  63. <!--MyabtisPlus 代码生成器-->
  64. <dependency>
  65. <groupId>com.baomidou</groupId>
  66. <artifactId>mybatis-plus-generator</artifactId>
  67. <version>3.5.3.1</version>
  68. </dependency>
  69. <dependency>
  70. <groupId>org.apache.velocity</groupId>
  71. <artifactId>velocity-engine-core</artifactId>
  72. <version>2.3</version>
  73. </dependency>
  74. </dependencies>
  75. <build>
  76. <sourceDirectory>${project.basedir}/src/main/kotlin</sourceDirectory>
  77. <testSourceDirectory>${project.basedir}/src/test/kotlin</testSourceDirectory>
  78. <plugins>
  79. <plugin>
  80. <groupId>org.springframework.boot</groupId>
  81. <artifactId>spring-boot-maven-plugin</artifactId>
  82. </plugin>
  83. <plugin>
  84. <groupId>org.jetbrains.kotlin</groupId>
  85. <artifactId>kotlin-maven-plugin</artifactId>
  86. <configuration>
  87. <args>
  88. <arg>-Xjsr305=strict</arg>
  89. </args>
  90. <compilerPlugins>
  91. <plugin>spring</plugin>
  92. </compilerPlugins>
  93. </configuration>
  94. <dependencies>
  95. <dependency>
  96. <groupId>org.jetbrains.kotlin</groupId>
  97. <artifactId>kotlin-maven-allopen</artifactId>
  98. <version>${kotlin.version}</version>
  99. </dependency>
  100. </dependencies>
  101. </plugin>
  102. </plugins>
  103. </build>
  104. </project>

三、SpringBoot配置文件

  1. server:
  2. port: 8080
  3. spring:
  4. datasource:
  5. url: jdbc:mysql://${MYSQL_HOST:localhost}:${MYSQL_PORT:3306}/${MYSQL_DB:demo}?useSSL=false&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&transformedBitIsBoolean=true&serverTimezone=Asia/Shanghai&nullCatalogMeansCurrent=true&allowPublicKeyRetrieval=true
  6. username: ${MYSQL_USERNAME:root}
  7. password: ${MYSQL_PWD:123456789}
  8. driverClassName: com.mysql.cj.jdbc.Driver
  9. ## Hikari 连接池配置
  10. hikari:
  11. ## 最小空闲连接数量
  12. minimum-idle: 10
  13. ## 空闲连接存活最大时间,默认600000(10分钟)
  14. idle-timeout: 18000
  15. ## 连接池最大连接数,默认是10
  16. maximum-pool-size: 1000
  17. ## 此属性控制从池返回的连接的默认自动提交行为,默认值:true
  18. auto-commit: true
  19. ## 连接池母子
  20. pool-name: DatebookHikariCP
  21. ## 此属性控制池中连接的最长生命周期,值0表示无限生命周期,默认1800000即30分钟
  22. max-lifetime: 1800000
  23. ## 数据库连接超时时间,默认30秒,即30000
  24. connection-timeout: 300000
  25. connection-test-query: SELECT 1
  26. jackson:
  27. date-format: yyyy-MM-dd HH:mm:ss
  28. time-zone: Asia/Shanghai
  29. mybatis-plus:
  30. mapper-locations: classpath*:mapper/*.xml,classpath*:mapping/*.xml
  31. #MyBatis 别名包扫描路径,通过该属性可以给包中的类注册别名,多个路径用逗号分割
  32. type-aliases-package: com.example.springboot.entity
  33. global-config:
  34. db-config:
  35. id-type: AUTO # 全局默认主键策略,默认为雪花ID,若表中设置了自增,则生成的实体自动添加自增ID属性,参考 TestDelete
  36. logic-delete-field: deleted # 全局逻辑删除的实体字段名,若不配置,则不启用
  37. logic-delete-value: 1 # 逻辑已删除值(默认为 1)
  38. logic-not-delete-value: 0 # 逻辑未删除值(默认为 0)
  39. configuration:
  40. map-underscore-to-camel-case: true # 驼峰转下划线(默认)
  41. log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 日志输出

四、代码生成工具

  1. package com.example.springboot
  2. import com.baomidou.mybatisplus.generator.AutoGenerator
  3. import com.baomidou.mybatisplus.generator.config.DataSourceConfig
  4. import com.baomidou.mybatisplus.generator.config.GlobalConfig
  5. import com.baomidou.mybatisplus.generator.config.PackageConfig
  6. import com.baomidou.mybatisplus.generator.config.StrategyConfig
  7. /**
  8. * 代码生成
  9. */
  10. fun main() {
  11. AutoGenerator(
  12. // 设置数据源
  13. /**
  14. * url: jdbc:mysql://localhost:3306/demo?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&AllowPublicKeyRetrieval=True
  15. * username: 用户名
  16. * password: 密码
  17. */
  18. DataSourceConfig.Builder(
  19. "jdbc:mysql://localhost:3306/demo?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&AllowPublicKeyRetrieval=True",
  20. "root",
  21. "123456789"
  22. ).build()
  23. ).run {
  24. // 全局配置
  25. global(
  26. GlobalConfig.Builder()
  27. // 启用 Kotlin
  28. .enableKotlin()
  29. /**
  30. * 输出路径
  31. * System.getProperty("user.dir") 得到的是这个项目的目录
  32. * /src/main/kotlin 是你代码的存放目录,如果你是多模块项目,记得加上你的模块名
  33. * 比如 service-oa-parent
  34. * |- service-oa
  35. * |- model
  36. * 你想在 service-oa 中生成,那么应该填入: System.getProperty("user.dir") + "/service-oa/src/main/kotlin"
  37. */
  38. .outputDir(System.getProperty("user.dir") + "/src/main/kotlin")
  39. // 作者
  40. .author("meng")
  41. // 设置生成完毕后是否展开你 idea 的目录,不影响结果
  42. .disableOpenDir()
  43. .build()
  44. )
  45. // 包信息配置
  46. packageInfo(
  47. PackageConfig.Builder()
  48. /**
  49. * 假定下列代码的目录结构为:
  50. * com.goxiaogle.auth
  51. * |- controller
  52. * |- service
  53. * |- impl
  54. * |- mapper
  55. * 则 com.goxiaogle 为父包,auth 为模块名
  56. */
  57. // 设置父包
  58. .parent("com.example")
  59. // 设置模块名
  60. .moduleName("springboot")
  61. // 以下四个可以去掉,如果你的分包命名和他一样
  62. // 设置 Controller 层包名,默认就是 controller
  63. .controller("controller")
  64. // 设置 Service 层包名,默认就是 service
  65. .service("service")
  66. // 设置 Mapper 层包名,默认就是 mapper
  67. .mapper("mapper")
  68. // 设置 Entity 包名,默认就是 entity
  69. .entity("entity")
  70. .build()
  71. )
  72. // 策略配置
  73. strategy(
  74. StrategyConfig.Builder()
  75. // 设置要生成代码的数据库表名,可以设置多个,如 addInclude(a, b, c)
  76. .addInclude("user")
  77. // 设置生成的 service 接口命名方式,默认是 IXxxService,这里改成 XxxService
  78. // serviceBuilder() 方法建议在 build 后使用,此处偷懒直接用了
  79. .serviceBuilder().formatServiceFileName("%sService")
  80. .mapperBuilder().enableFileOverride().enableBaseColumnList().enableBaseResultMap()
  81. .build()
  82. // 设置其它几层的内容
  83. // .entityBuilder()
  84. // .controllerBuilder()
  85. // .mapperBuilder().build()
  86. )
  87. // 执行
  88. execute()
  89. }
  90. }

五、实现用户服务模块案例

1、Controller

  1. package com.example.springboot.controller;
  2. import com.example.springboot.entity.UserEntity
  3. import com.example.springboot.service.UserService
  4. import org.springframework.web.bind.annotation.RequestMapping;
  5. import org.springframework.web.bind.annotation.PostMapping
  6. import org.springframework.web.bind.annotation.RestController
  7. import javax.annotation.Resource
  8. import javax.servlet.http.HttpServletRequest
  9. /**
  10. * <p>
  11. * 用户服务
  12. * </p>
  13. *
  14. * @author meng
  15. * @since 2024-02-03
  16. */
  17. @RestController
  18. @RequestMapping("/user")
  19. class UserController {
  20. // 需要注意和java不同的是,如果有bean的注入,需要在前面加上lateinit
  21. @Resource
  22. lateinit var userService: UserService;
  23. @PostMapping("/getUserById")
  24. fun getUserById(req: HttpServletRequest): UserEntity {
  25. val id: String = req.getParameter("id")
  26. val info: UserEntity = userService.findUserById(id)
  27. return info
  28. }
  29. }

2、Service

  1. package com.example.springboot.service;
  2. import com.example.springboot.entity.UserEntity;
  3. import com.baomidou.mybatisplus.extension.service.IService;
  4. /**
  5. * <p>
  6. * 服务类
  7. * </p>
  8. *
  9. * @author meng
  10. * @since 2024-02-03
  11. */
  12. interface UserService : IService<UserEntity> {
  13. fun findUserById(userId: String): UserEntity
  14. }
  1. package com.example.springboot.service.impl;
  2. import com.example.springboot.entity.UserEntity;
  3. import com.example.springboot.mapper.UserMapper;
  4. import com.example.springboot.service.UserService;
  5. import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
  6. import org.springframework.stereotype.Service;
  7. import javax.annotation.Resource
  8. /**
  9. * <p>
  10. * 服务实现类
  11. * </p>
  12. *
  13. * @author meng
  14. * @since 2024-02-03
  15. */
  16. @Service
  17. open class UserServiceImpl : ServiceImpl<UserMapper, UserEntity>(), UserService {
  18. @Resource
  19. lateinit var userMapper: UserMapper
  20. override fun findUserById(userId: String): UserEntity {
  21. return userMapper.findUserById(userId)
  22. }
  23. }

3、Entity

  1. package com.example.springboot.entity;
  2. import java.io.Serializable;
  3. /**
  4. * <p>
  5. *
  6. * </p>
  7. *
  8. * @author meng
  9. * @since 2024-02-03
  10. */
  11. class UserEntity : Serializable {
  12. var id: String? = null
  13. var name: String? = null
  14. override fun toString(): String {
  15. return "User{" +
  16. "id=" + id +
  17. ", name=" + name +
  18. "}"
  19. }
  20. }

4、Mapper

  1. package com.example.springboot.mapper;
  2. import com.example.springboot.entity.UserEntity;
  3. import com.baomidou.mybatisplus.core.mapper.BaseMapper;
  4. import org.apache.ibatis.annotations.Mapper
  5. /**
  6. * <p>
  7. * Mapper 接口
  8. * </p>
  9. *
  10. * @author meng
  11. * @since 2024-02-03
  12. */
  13. @Mapper
  14. interface UserMapper : BaseMapper<UserEntity> {
  15. //根据id获取用户信息
  16. fun findUserById(id: String): UserEntity
  17. }

xml:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3. <mapper namespace="com.example.springboot.mapper.UserMapper">
  4. <!-- 通用查询映射结果 -->
  5. <resultMap id="BaseResultMap" type="com.example.springboot.entity.UserEntity">
  6. <id column="id" property="id" />
  7. <result column="name" property="name" />
  8. </resultMap>
  9. <!-- 通用查询结果列 -->
  10. <sql id="Base_Column_List">
  11. id, name
  12. </sql>
  13. <select id="findUserById" resultMap="BaseResultMap" >
  14. SELECT
  15. <include refid="Base_Column_List" />
  16. FROM user
  17. WHERE id = #{id}
  18. </select>
  19. </mapper>

5、接口测试

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/1009337
推荐阅读
相关标签
  

闽ICP备14008679号