Kotlin + SpringBoot + JPA 服务端开发

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

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 等等..

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_8configurations {    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 kotlinspringbootdemoimport org.springframework.boot.autoconfigure.SpringBootApplicationimport org.springframework.boot.runApplication@SpringBootApplicationclass KotlinSpringBootApplicationfun main(args: Array<String>) {    runApplication<KotlinSpringBootApplication>(*args)}
2.3 编写Controller
能够看到controller 和 Java 写法 根本差不多 是不是很像
@RestControllerclass 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

能够看到胜利返回了数据

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 插件治理

//引入JPAimplementation("org.springframework.boot:spring-boot-starter-data-jpa")//引入 Mysqlimplementation("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.entityimport 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 */@Repositoryinterface StudentRepository : JpaRepository<StudentInfo,Long> {}
3.7 增加一个接口测试
除了lateinit 标注 注入的 属性 提早初始化, 其余的和Java 外面用没啥区别
@RestControllerclass 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    }}

总结

本篇次要介绍 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小屋
欢送关注集体公众号