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:
Add the
@Tableannotation to theMessageclass to declare mapping to a database table.
Add the@Idannotation before theidfield.// Message.kt package demo import org.springframework.data.annotation.Id import org.springframework.data.relational.core.mapping.Table @Table("MESSAGES") data class Message(@Id val id: String?, val text: String)In addition, to make the use of the
Messageclass more idiomatic, you can set the default value foridproperty to null and flip the order of the data class properties:@Table("MESSAGES") data class Message(val text: String, @Id val id: String? = null)Now if you need to create a new instance of the
Messageclass, you can only specify thetextproperty as a parameter:val message = Message("Hello") // id is nullDeclare an interface for the
CrudRepositorythat will work with theMessagedata class. Create theMessageRepository.ktfile and add the following code to it:// MessageRepository.kt package demo import org.springframework.data.repository.CrudRepository interface MessageRepository : CrudRepository<Message, String>Update the
MessageServiceclass. It will now use theMessageRepositoryinstead of executing SQL queries:// MessageService.kt package demo import org.springframework.data.repository.findByIdOrNull import org.springframework.stereotype.Service @Service class MessageService(private val db: MessageRepository) { fun findMessages(): List<Message> = db.findAll().toList() fun findMessageById(id: String): Message? = db.findByIdOrNull(id) fun save(message: Message): Message = db.save(message) }- Extension functions
The
findByIdOrNull()function is an extension function forCrudRepositoryinterface in Spring Data JDBC.- CrudRepository save() function
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,
CrudRepositoryassumes that the object already exists in the database and this is an update operation as opposed to an insert operation. After the insert operation, theidwill be generated by the data store and assigned back to theMessageinstance. This is why theidproperty should be declared using thevarkeyword.
Update the messages table definition to generate the ids for the inserted objects. Since
idis a string, you can use theRANDOM_UUID()function to generate the id value by default:-- schema.sql CREATE TABLE IF NOT EXISTS messages ( id VARCHAR(60) DEFAULT RANDOM_UUID() PRIMARY KEY, text VARCHAR NOT NULL );Update the name of the database in the
application.propertiesfile located in thesrc/main/resourcesfolder:spring.application.name=demo spring.datasource.driver-class-name=org.h2.Driver spring.datasource.url=jdbc:h2:file:./data/testdb2 spring.datasource.username=name spring.datasource.password=password spring.sql.init.schema-locations=classpath:schema.sql spring.sql.init.mode=always
Here is the complete code of the application:
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.
What's next
Get your personal language map to help you navigate Kotlin features and track your progress in studying the language:
Learn more about Calling Java from Kotlin code and Calling Kotlin from Java code.
Learn how to convert existing Java code to Kotlin with the Java-to-Kotlin converter.
Check out our Java to Kotlin migration guides:
