ICode9

精准搜索请尝试: 精确搜索
首页 > 系统相关> 文章详细

Kotlin + SpringBoot + JPA 服务端开发

2022-12-27 17:09:05  阅读:400  来源: 互联网

标签:c++ icode9 函数 swap 语言 C语言 代码 构建 google


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_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;

SQL 复制 全屏

3.6 编写Repository

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

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

标签:c++,icode9,函数,swap,语言,C语言,代码,构建,google
来源:

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有