编程知识 cdmana.com

SpringBoot-Kotlin

What is? Kotlin?

Kotlin( Colin ) Is a static programming language for modern multi platform applications , from JetBrains Development .

Kotlin Can be compiled into Java Bytecode , It can also be compiled into JavaScript, Is it convenient JVM Running on your device . besides Kotlin It can also be compiled into binary code and run directly on the machine ( For example, embedded devices or iOS). [2]

Kotlin Has officially become Android Official support for development languages .

file

Let's take a look first Kotlin The address of the document

Kotlin Chinese document :https://kotlinlang.org/

Kotlin English document :https://www.kotlincn.net/

grammar

Briefly introduce several different grammars

attribute

Kotlin The attributes in the class can be used as keywords var Declare variable , You can also use keywords val Declared read-only .

Variable

Define read-only local variables using the keyword val Definition . It can only be assigned once .

The variable that can be reassigned uses var keyword

Implementation interface

class Child : MyInterface {
    override fun bar() {
        //  Method body 
    }
}

Null and null testing

When the value of a variable can be null When , You must add... After the type at the declaration ? To identify that the reference can be empty .

fun parseInt(str: String): Int? {}

When expression

when Expressions replace classes java Linguistic switch sentence . Its simplest form is as follows :

when (x) {
    1 -> print("x == 1")
    2 -> print("x == 2")
    else -> { //  Pay attention to this block 
        print("x is neither 1 nor 2")
    }
}

If when Use as an expression , Must have else Branch

There are still many differences in grammar , If you are interested, you can check the official documents , Poor English skills , Chinese documents are recommended , It's not hard , The translation is also more accurate

SpringBoot Integrate Kotlin

As java For developers, priority must be SpringBoot Integrate kotlin, Simple and easy to use

Let's take a look at dependency , If you have enough confidence in your network , You can not configure maven Warehouse , Otherwise, you will find that you need to wait a century

import org.jetbrains.kotlin.gradle.tasks.KotlinCompile

plugins {
    id("org.springframework.boot") version "2.4.0"
    id("io.spring.dependency-management") version "1.0.10.RELEASE"
    kotlin("jvm") version "1.4.10"
    kotlin("plugin.spring") version "1.4.10"
}

group = "top.lzmvlog"
version = "0.0.1-SNAPSHOT"
java.sourceCompatibility = JavaVersion.VERSION_11

repositories {
    maven {
        url = uri("https://maven.aliyun.com/repository/central")
    }
    maven {
        url = uri("https://maven.aliyun.com/repository/spring")
    }
    maven {
        url = uri("https://maven.aliyun.com/repository/gradle-plugin")
    }
    mavenCentral()
}

dependencies {
    implementation("org.springframework.boot:spring-boot-starter-webflux")
    implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
    implementation("io.projectreactor.kotlin:reactor-kotlin-extensions")
    implementation("org.jetbrains.kotlin:kotlin-reflect")
    implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-reactor")
    compileOnly("org.projectlombok:lombok")
    compileOnly("com.baomidou:mybatis-plus-boot-starter:3.1.0")
    runtimeOnly("mysql:mysql-connector-java")
    annotationProcessor("org.projectlombok:lombok")
    testImplementation("org.springframework.boot:spring-boot-starter-test")
    testImplementation("io.projectreactor:reactor-test")
}

tasks.withType<KotlinCompile> {
    kotlinOptions {
        freeCompilerArgs = listOf("-Xjsr305=strict")
        jvmTarget = "11"
    }
}

tasks.withType<Test> {
    useJUnitPlatform()
}

ymal To configure

server:
  port: 9090

spring:
  application:
    name: authority
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/myschool?useUnicode=true&characterEncoding=utf8&useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=GMT%2B8
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver

mybatis-plus:
  mapper-locations: classpath:/mapper/*.mapper
  type-aliases-package: top.lzmvlog.demokotlin.model
  configuration:
    cache-enabled: true
    call-setters-on-nulls: true
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

First, follow the programming conventions , A first Hello World Say hello

@RestController
class IndexController {

    @GetMapping("hello")
    fun hello(): String {
        return "Hello World"
    }
}

Let's just add, delete, modify and check , Look at the database first , A student list that has remained unchanged for ten thousand years , Mainly want to be lazy

-- ----------------------------
-- Table structure for student
-- ----------------------------
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student`  (
  `id` varchar(225) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `name` varchar(225) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `age` int(0) NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of student
-- ----------------------------
INSERT INTO `student` VALUES ('0', ' Zhang San ', 20);
INSERT INTO `student` VALUES ('1', ' Young hero ', 20);
INSERT INTO `student` VALUES ('2', ' zhaoyun ', 20);

MybatisPlus It's easy to operate , Just take this as an example

model

data class Student(
        var id: Int,
        var name: String,
        var age: Int
)

data class Create a containing getterssettersequals()hashCode()toString() as well as copy() Of POJO, Call the expert ,Lombok No need

Kotlin The grammar of , If there is no logic in the class, you can omit parentheses

Mapper

@Mapper
interface StudentMapper : BaseMapper<Student> {}

Service

 interface StudentService {

    /**
     *  Query student collection 
     */
    fun selectList(): List<Student>

    /**
     *  Save student information 
     */
    fun save(student: Student): Int

    /**
     *  According to the students id Delete 
     */
    fun delete(id: Int): Int

    /**
     *  Update student information 
     */
    fun update(student: Student): Int

    /**
     *  Paging query student information 
     */
    fun selectPage(page: Page<Student>): IPage<Student>

}

ServiceImpl

@Service
class StudentServiceImpl : StudentService {

    @Autowired
    lateinit var studentMapper: StudentMapper

    /**
     *  Query all students 
     */
    override fun selectList(): List<Student> {
        return studentMapper.selectList(Wrappers.query())
    }

    /**
     *  Save student information 
     */
    override fun save(student: Student): Int {
        return studentMapper.insert(student)
    }

    /**
     *  According to the students id Delete 
     */
    override fun delete(id: Int): Int {
        return studentMapper.deleteById(id)
    }

    /**
     *  Update student information 
     */
    override fun update(student: Student): Int {
        return studentMapper.updateById(student)
    }

    /**
     *  Paging query student information 
     */
    override fun selectPage(page: Page<Student>): IPage<Student> {
        return studentMapper.selectPage(page, Wrappers.query())
    }
}

Controller

@RestController
class StudentController {

    @Autowired
    lateinit var studentServiceImpl: StudentServiceImpl

    /**
     *  Search for student information 
     */
    @GetMapping("select")
    fun select(): List<Student> {
        return studentServiceImpl.selectList()
    }

    /**
     *  Save student information 
     */
    @PostMapping("save")
    fun save(@RequestBody student: Student): String {
        val save = studentServiceImpl.save(student)
        if (save == 1) {
            return " Saved successfully "
        }
        return " Save failed "
    }

    /**
     *  According to the students id Delete student information 
     */
    @DeleteMapping("delete/{id}")
    fun delete(@PathVariable id: Int): String {
        val delete = studentServiceImpl.delete(id)
        if (delete == 1) {
            return " Delete successful "
        }
        return " Delete failed "
    }

    /**
     *  Modify student information 
     */
    @PostMapping("update")
    fun update(@RequestBody student: Student): String {
        val update = studentServiceImpl.update(student)
        if (update == 1) {
            return " Modification successful "
        }
        return " Modification failed "
    }

    /**
     *  Modify student information 
     */
    @PostMapping("selectPage")
    fun selectPage(page: Page<Student>): IPage<Student> {
        return studentServiceImpl.selectPage(page);
    }

}
server:
  port: 9090

spring:
  application:
    name: authority
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/myschool?useUnicode=true&characterEncoding=utf8&useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=GMT%2B8
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver

mybatis-plus:
  mapper-locations: classpath:/mapper/*.mapper
  type-aliases-package: top.lzmvlog.demokotlin.model
  configuration:
    cache-enabled: true
    call-setters-on-nulls: true
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

Except grammar and Java There's a difference , Everything else is not much , There's nothing special or different , The only thing to notice is that gradle When packing , Can't detect SpringBoot The test class , Annotation packaging will become normal , I don't quite understand why , If there is a solution , Welcome to advise !

You come on ! distance 2020 It's not long since the year ended , Origie !

Participation of this paper Tencent cloud media sharing plan , You are welcome to join us , share .

版权声明
本文为[Shao Jie]所创,转载请带上原文链接,感谢
https://cdmana.com/2021/08/20210809183600772C.html

Scroll to Top