使用 Spring Data CrudRepository 进行数据库访问

This is the final part of the Getting started with Spring Boot and Kotlin tutorial. Before proceeding, make sure you’ve completed previous steps:

Figt step Create a Spring Boot project with Kotlin
Second step Add a data class to the Spring Boot project
Third step Add database support for Spring Boot project
Fourth step Use Spring Data CrudRepository for database access

In this part, you will migrate the service layer to use the Spring Data CrudRepository instead of JdbcTemplate for database access. CrudRepository is a Spring Data interface for generic CRUD operations on a repository of a specific type. It provides several methods out of the box for interacting with a database.

Update your application

First, you need to adjust the Message class for work with the CrudRepository API:

  1. Add the @Table annotation to the Message class to declare mapping to a database table.
    Add the @Id annotation before the id field.

    These annotations also require additional imports.

    使用 Spring Data CrudRepository 进行数据库访问 - 图5

    1. import org.springframework.data.annotation.Id
    2. import org.springframework.data.relational.core.mapping.Table
    3. @Table("MESSAGES")
    4. data class Message(@Id var id: String?, val text: String)

    Besides adding the annotations, you also need to make the id mutable (var) for the reasons of how CrudRepository works when inserting the new objects to the database.

  2. Declare an interface for the CrudRepository that will work with the Message data class:

    1. import org.springframework.data.repository.CrudRepository
    2. interface MessageRepository : CrudRepository<Message, String>
  3. Update the MessageService class. It will now call to the MessageRepository instead of executing SQL queries:

    1. import java.util.*
    2. @Service
    3. class MessageService(val db: MessageRepository) {
    4. fun findMessages(): List<Message> = db.findAll().toList()
    5. fun findMessageById(id: String): List<Message> = db.findById(id).toList()
    6. fun save(message: Message) {
    7. db.save(message)
    8. }
    9. fun <T : Any> Optional<out T>.toList(): List<T> =
    10. if (isPresent) listOf(get()) else emptyList()
    11. }

    The return type of the findById() function in the CrudRepository interface is an instance of the Optional class. However, it would be convenient to return a List with a single message for consistency. For that, you need to unwrap the Optional value if it’s present, and return a list with the value. This can be implemented as an extension function to the Optional type.

    In the code, Optional<out T>.toList(), .toList() is the extension function for Optional. Extension functions allow you to write additional functions to any classes, which is especially useful when you want to extend functionality of some library class.

    This function works with an assumption that the new object doesn’t have an id in the database. Hence, the id should be null for insertion.

    If the id isn’t null, CrudRepository assumes that the object already exists in the database and this is an update operation as opposed to an insert operation. After the insert operation, the id will be generated by the data store and assigned back to the Message instance. This is why the id property should be declared using the var keyword.

  4. Update the messages table definition to generate the ids for the inserted objects. Since id is a string, you can use the RANDOM_UUID() function to generate the id value by default:

    1. CREATE TABLE IF NOT EXISTS messages (
    2. id VARCHAR(60) DEFAULT RANDOM_UUID() PRIMARY KEY,
    3. text VARCHAR NOT NULL
    4. );
  5. Update the name of the database in the application.properties file located in the src/main/resources folder:

    1. spring.datasource.driver-class-name=org.h2.Driver
    2. spring.datasource.url=jdbc:h2:file:./data/testdb2
    3. spring.datasource.username=name
    4. spring.datasource.password=password
    5. spring.sql.init.schema-locations=classpath:schema.sql
    6. spring.sql.init.mode=always

Here is the complete code for DemoApplication.kt:

  1. package com.example.demo
  2. import org.springframework.boot.autoconfigure.SpringBootApplication
  3. import org.springframework.boot.runApplication
  4. import org.springframework.data.annotation.Id
  5. import org.springframework.data.relational.core.mapping.Table
  6. import org.springframework.data.repository.CrudRepository
  7. import org.springframework.stereotype.Service
  8. import org.springframework.web.bind.annotation.*
  9. import java.util.*
  10. @SpringBootApplication
  11. class DemoApplication
  12. fun main(args: Array<String>) {
  13. runApplication<DemoApplication>(*args)
  14. }
  15. @RestController
  16. class MessageController(val service: MessageService) {
  17. @GetMapping("/")
  18. fun index(): List<Message> = service.findMessages()
  19. @GetMapping("/{id}")
  20. fun index(@PathVariable id: String): List<Message> =
  21. service.findMessageById(id)
  22. @PostMapping("/")
  23. fun post(@RequestBody message: Message) {
  24. service.save(message)
  25. }
  26. }
  27. interface MessageRepository : CrudRepository<Message, String>
  28. @Table("MESSAGES")
  29. data class Message(@Id var id: String?, val text: String)
  30. @Service
  31. class MessageService(val db: MessageRepository) {
  32. fun findMessages(): List<Message> = db.findAll().toList()
  33. fun findMessageById(id: String): List<Message> = db.findById(id).toList()
  34. fun save(message: Message) {
  35. db.save(message)
  36. }
  37. fun <T : Any> Optional<out T>.toList(): List<T> =
  38. if (isPresent) listOf(get()) else emptyList()
  39. }

Run the application

The application is ready to run again. By replacing the JdbcTemplate with CrudRepository, the functionality didn’t change hence the application should work the same way as previously.

Next step

Get your personal language map to help you navigate Kotlin features and track your progress in studying the language. We will also send you language tips and useful materials on using Kotlin with Spring.

Get the Kotlin language map

You will need to share your email address on the next page to receive the materials.

使用 Spring Data CrudRepository 进行数据库访问 - 图7