Spring Boot R2DBC MySQL CRUD Kotlin

2,221 阅读1分钟

R2DBC 还未完全成熟,现在声明式事务还有点问题,所有文章只简单的写了 kotlin协程 + CRUD

1、依赖管理

第一步 添加相关的 pom 依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.3.2.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.sweet</groupId>
	<artifactId>ktdemo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>ktdemo</name>
	<description>Demo project for Spring Boot</description>

	<properties>
		<java.version>1.8</java.version>
		<kotlin.version>1.3.72</kotlin.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-r2dbc</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-webflux</artifactId>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.module</groupId>
			<artifactId>jackson-module-kotlin</artifactId>
		</dependency>
		<dependency>
			<groupId>io.projectreactor.kotlin</groupId>
			<artifactId>reactor-kotlin-extensions</artifactId>
		</dependency>
		<dependency>
			<groupId>org.jetbrains.kotlin</groupId>
			<artifactId>kotlin-reflect</artifactId>
		</dependency>
		<dependency>
			<groupId>org.jetbrains.kotlin</groupId>
			<artifactId>kotlin-stdlib-jdk8</artifactId>
		</dependency>
		<dependency>
			<groupId>org.jetbrains.kotlinx</groupId>
			<artifactId>kotlinx-coroutines-reactor</artifactId>
		</dependency>

		<dependency>
			<groupId>dev.miku</groupId>
			<artifactId>r2dbc-mysql</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintage</groupId>
					<artifactId>junit-vintage-engine</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>io.projectreactor</groupId>
			<artifactId>reactor-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<sourceDirectory>${project.basedir}/src/main/kotlin</sourceDirectory>
		<testSourceDirectory>${project.basedir}/src/test/kotlin</testSourceDirectory>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
			<plugin>
				<groupId>org.jetbrains.kotlin</groupId>
				<artifactId>kotlin-maven-plugin</artifactId>
				<configuration>
					<args>
						<arg>-Xjsr305=strict</arg>
					</args>
					<compilerPlugins>
						<plugin>spring</plugin>
					</compilerPlugins>
				</configuration>
				<dependencies>
					<dependency>
						<groupId>org.jetbrains.kotlin</groupId>
						<artifactId>kotlin-maven-allopen</artifactId>
						<version>${kotlin.version}</version>
					</dependency>
				</dependencies>
			</plugin>
		</plugins>
	</build>

</project>

2. 数据库配置

R2DBC 的配置和原来的 JDBC配置不同

server.port=9070

spring.r2dbc.url=r2dbc:mysql://localhost:3306/cat1?characterEncoding=UTF-8&useSSL=true
spring.r2dbc.username=root
spring.r2dbc.password=123456

logging.level.com.sweet.ktdemo=DEBUG
logging.level.org.springframework.data.r2dbc=DEBUG

最后一句可以打印出执行的 sql

3. 模型类

data class User(val id: Long, val name: String)

4. Repository

package com.sweet.ktdemo.repository

import com.sweet.ktdemo.model.User
import kotlinx.coroutines.reactive.awaitFirst
import org.springframework.data.r2dbc.core.*
import org.springframework.data.relational.core.query.Criteria
import org.springframework.data.relational.core.query.Update
import org.springframework.stereotype.Service

@Service
class UserRepository(val client: DatabaseClient) {

    suspend fun findOne(id: Long): User? =
            client.execute("SELECT * FROM t_user where id=:id")
                    .bind("id", id)
                    .asType<User>()
                    .fetch()
                    .awaitFirst()

    suspend fun findAll(): MutableList<User> = client.select().from("t_user")
            .asType<User>()
            .fetch()
            .all()
            .collectList()
            .awaitFirst()

    suspend fun save(user: User) =
            client.insert().into<User>().table("t_user")
                    .using(user)
                    .await()

    suspend fun saveAll(user: List<User>) {
        user.forEach { save(it) }
    }

    suspend fun delete(id: Long) =
            client.delete()
                    .from("t_delete")
                    .matching(Criteria.where("id").`is`(id))
                    .fetch().awaitRowsUpdated()

    suspend fun update(user: User) =
            client.update()
                    .table("t_user")
                    .using(Update.update("name", user.name))
                    .matching(Criteria.where("id").`is`(user.id))
                    .fetch()
                    .awaitRowsUpdated()

}

5. Controller

package com.sweet.ktdemo.controller

import com.sweet.ktdemo.model.User
import com.sweet.ktdemo.repository.UserRepository
import org.springframework.web.bind.annotation.*

@RestController
class UserController(val userRepository: UserRepository) {

    @GetMapping("/user/{id}")
    suspend fun getUser(@PathVariable id: Long): User? =
            userRepository.findOne(id)

    @GetMapping("/users")
    suspend fun getUsers(): List<User> =
            userRepository.findAll()

    @PostMapping("/users")
    suspend fun saveUser(@RequestBody users: List<User>): Unit =
            userRepository.saveAll(users)

    @DeleteMapping("/users/{id}")
    suspend fun deleteUser(@PathVariable id: Long): Int =
            userRepository.delete(id)

    @PutMapping("/users")
    suspend fun updateUser(@RequestBody user: User): Int =
            userRepository.update(user)
}
  1. 测试接口 api-test.http
PUT http://localhost:9070/users
Content-Type: application/json

{
  "id" : 1,
  "name" : "faef0000Update"
}

###
DELETE http://localhost:9070/users/46
Accept: application/json

###
POST http://localhost:9070/users
Content-Type: application/json

[
  {
    "id" : 190,
    "name" : "Kt01"
  },
  {
    "id" : 20,
    "name" : "Kt02"
  }
]

###
GET http://localhost:9070/users
Accept: application/json

###

GET http://localhost:9070/user/1
Accept: application/json

### 根据 ID 获取