Kotlin + SpringBoot + JPA 服务端开发

376 阅读4分钟

Kotlin + SpringBoot + JPA 服务端开发

本篇主要介绍一下 kotlin + springboot的服务端开发环境搭建

image-20221217230259948

1.概述

Kotlin 是一个基于JVM的编程语言, 是IDEA开发工具 jetbrains 公司开发的语言,也被google选为android开发的首选语言, 因为它是完全兼容Java的 所以也可以做后端开发 比如集成我们在使用Java的一些技术框架 ,本篇就来简单介绍一下和SpringBoot的集成

下面我用Gradle init 的方式从头开始搭建Kotlin 集成SpringBoot环境, 你也可以通过IDEA直接创建 SpringBoot项目里面选择Kotlin语言即可, 我这里不展示了

2.Gradle init 初始化项目

可以通过gradle init 命令初始化项目 按照提示 选择 kotlin语言 , kotlin dsl 等等..

image-20221217065630353

2.1 插件配置

需要配置几个插件 包括 springboot gradle 插件

  • org.springframework.boot

    Spring Boot 官方提供了Gradle插件支持,可以打包程序为可执行的 jar 或 war 包,运行 Spring Boot 应用程序,并且使用spring-boot-dependencies 管理版本

  • io.spring.dependency-management

    自动从你正在使用的springbooot版本中导入spring-boot-dependencies bom

  • kotlin("jvm") : 指定kotlin的版本

  • kotlin("plugin.spring") : 用于在给类添加 open 关键字(否则是final的) 仅限于spring的一些注解比如@Controller

    @Service ..

  • kotlin("plugin.jpa") : 用于生成kotlin 数据类 无参构造函数,否则会提示Entity缺少缺省构造函数

plugins {
    // Apply the org.jetbrains.kotlin.jvm Plugin to add support for Kotlin.
    // id("org.jetbrains.kotlin.jvm") version "1.7.10"
    id("org.springframework.boot") version "2.6.11"
    id("io.spring.dependency-management") version "1.0.13.RELEASE"
    kotlin("jvm") version "1.6.21"
    //引入spring插件 可以给 一些spring注解的类 添加 open关键字 解决kotlin 默认final问题
    kotlin("plugin.spring") version "1.6.21"
    //引入jpa插件 主要可以给JPA的一些注解类添加 无参构造函数
    kotlin("plugin.jpa") version "1.6.21"
    // Apply the application plugin to add support for building a CLI application in Java.
}


java.sourceCompatibility = JavaVersion.VERSION_1_8

configurations {
    compileOnly {
        extendsFrom(configurations.annotationProcessor.get())
    }
}

dependencies {
    // Use the Kotlin JUnit 5 integration.
    testImplementation("org.jetbrains.kotlin:kotlin-test-junit5")

    // Use the JUnit 5 integration.
    testImplementation("org.junit.jupiter:junit-jupiter-engine:5.9.1")

    // This dependency is used by the application.
    implementation("com.google.guava:guava:31.1-jre")
  
    implementation("org.jetbrains.kotlin:kotlin-reflect")
    implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")

    //引入springboot web依赖
    implementation("org.springframework.boot:spring-boot-starter-web")

}

tasks.named<Test>("test") {
    // Use JUnit Platform for unit tests.
    useJUnitPlatform()
}


tasks.withType<org.jetbrains.kotlin.gradle.tasks.KotlinCompile> {
    kotlinOptions {
        freeCompilerArgs = listOf("-Xjsr305=strict")
        jvmTarget = "1.8"
    }
}

2.2 编写SpringBoot启动类

直接手动创建一个即可, 内容和 原生Java 差不多 因为添加了 plugin.spring所以不需要添加open关键字了

package kotlinspringbootdemo

import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
@SpringBootApplication
class KotlinSpringBootApplication

fun main(args: Array<String>) {
    runApplication<KotlinSpringBootApplication>(*args)
}

2.3 编写Controller

可以看到controller 和 Java 写法 基本差不多 是不是很像

@RestController
class HelloController {

    data class KotlinInfo(val name: String, val desc: String)

    @GetMapping("/getKotlin")
    fun getKotlinSpringBoot(): KotlinInfo {
        return KotlinInfo("kotlin", "kotlin springboot")
    }
}

2.4 配置application.yaml

在resources 下面创建一个 application.yaml文件即可

server:
  port: 8899

2.5 测试接口 /getKotlin

可以看到成功返回了数据

image-20221217224053808

3.集成JPA

下面来看看如何集成JPA

3.1 引入jpa插件

这个插件的作用是给 @Entity 等JPA的实体 添加 无参构造方法的, 下面是spring官网对这个插件的解释

In order to be able to use Kotlin non-nullable properties with JPA, Kotlin JPA plugin is also enabled. It generates no-arg constructors for any class annotated with @Entity, @MappedSuperclass or @Embeddable.

//引入jpa插件 
kotlin("plugin.jpa") version "1.6.21"

3.2 引入jpa 和 mysql

jpa的版本由 dependency-management 插件管理

//引入JPA
implementation("org.springframework.boot:spring-boot-starter-data-jpa")
//引入 Mysql
implementation("mysql:mysql-connector-java:8.0.30")

3.3 application.yaml 数据库配置

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/kotlinweb?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false
    username: root
    password: root123456

3.4 编写一个Entity

注意哈是 () 构造方法定义的这些属性 , 这是kotlin的构造函数的写法

package kotlinspringbootdemo.entity

import javax.persistence.*

/**
 * Created on 2022/12/17 21:28.
 * @author Johnny
 */
@Entity
@Table(name = "student")
class StudentInfo(
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    val id: Long = 0,

    @Column(name = "name")
    val name: String,

    @Column(name = "email")
    val email: String,

    @Column(name = "address")
    val address: String
)

3.5 student表创建

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for student
-- ----------------------------
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
  `id` bigint NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `email` varchar(255) DEFAULT NULL,
  `address` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

SET FOREIGN_KEY_CHECKS = 1;

3.6 编写Repository

jpa需要定义 repository 这是jpa的知识范围 不多介绍

/**
 * @author Johnny
 */
@Repository
interface StudentRepository : JpaRepository<StudentInfo,Long> {
}

3.7 添加一个接口测试

除了lateinit 标注 注入的 属性 延迟初始化, 其他的和Java 里面用没啥区别

@RestController
class HelloController {
		//注意是 lateinit 延迟初始化
    @Autowired
    lateinit var studentRepository: StudentRepository

    @GetMapping("/add")
    fun addStudent(): StudentInfo {
        val studentInfo = StudentInfo(name = "johnny", email = "626242589@qq.com", address = "江苏无锡")
        studentRepository.save(studentInfo)
        return studentInfo
    }
}

image-20221217225449284

总结

本篇主要介绍 kotlin springboot 和 jpa的环境搭建和基本使用, 可以看到 基本和java的那套没啥区别

主要是插件那块要弄清楚 这些插件 kotlin spring jpa boot dependency-manager 等等都是干嘛的

//用法一: 这个插件 用于在给类添加 open 关键字(否则是final的)  仅限于spring的一些注解比如@Controller @Service ..等等.
kotlin("plugin.spring") version "1.6.21" 

//用法二
id("org.jetbrains.kotlin.plugin.allopen") version "1.6.21"
allOpen{
    //把需要open 注解标注的类添加上来
    annotation("org.springframework.boot.autoconfigure.SpringBootApplication")
    annotation("org.springframework.web.bind.annotation.RestController")
}

//用法三 
id("org.jetbrains.kotlin.plugin.allopen") version "1.6.21"
apply{
    plugin("kotlin-spring")
}

//详细可以看 : https://kotlinlang.org/docs/all-open-plugin.html#spring-support

欢迎大家访问 个人博客 Johnny小屋
欢迎关注个人公众号

欢迎关注个人公众号