Kotlin is a statically typed programming language that runs on the Java Virtual Machine and can also be compiled to JavaScript source code. Kotlin is developed by JetBrains.
Spring Data is a project that makes it easier to work with data access technologies, such as relational databases, in the Spring Framework.
In this article, we'll see how to use Kotlin and Spring Data to connect to a database.
First, we'll need to create a new Kotlin project using the Spring Initializr. We'll need to select the following dependencies:
Once the project has been generated, we can import it into our favorite IDE. I'll be using IntelliJ IDEA.
Next, we'll need to configure the DataSource. We can do this by adding the following to the application.properties
file:
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=create-drop
The spring.datasource.url
property defines the URL of the database. The spring.datasource.driverClassName
property defines the driver class name. The spring.datasource.username
property defines the username. The spring.datasource.password
property defines the password.
The spring.jpa.generate-ddl
property tells Spring Data to generate the database schema. The spring.jpa.hibernate.ddl-auto
property tells Hibernate to create and drop the database schema.
Next, we'll need to create an entity. An entity is a class that represents a table in the database. We can create an entity by annotating a class with the @Entity
annotation.
@Entity
class User(
@Id @GeneratedValue val id: Long,
val name: String,
val age: Int
)
The @Entity
annotation indicates that this is an entity. The @Id
annotation indicates that the id
property is the primary key. The @GeneratedValue
annotation indicates that the id
property should be generated by the database.
The name
and age
properties will be mapped to columns in the database.
Next, we'll need to create a repository. A repository is a class that provides access to the data in the database. We can create a repository by annotating a class with the @Repository
annotation.
@Repository
interface UserRepository : CrudRepository<User, Long>
The @Repository
annotation indicates that this is a repository. The CrudRepository
interface provides methods for CRUD operations.
Next, we'll need to create a service. A service is a class that contains business logic. We can create a service by annotating a class with the @Service
annotation.
@Service
class UserService(
private val userRepository: UserRepository
) {
fun createUser(user: User): User {
return userRepository.save(user)
}
fun getUserById(id: Long): User? {
return userRepository.findById(id).orElse(null)
}
fun getAllUsers(): List<User> {
return userRepository.findAll().toList()
}
fun updateUser(user: User): User {
return userRepository.save(user)
}
fun deleteUserById(id: Long) {
userRepository.deleteById(id)
}
}
The @Service
annotation indicates that this is a service. The createUser
method creates a new user. The getUserById
method gets a user by id. The getAllUsers
method gets all users. The updateUser
method updates a user. The deleteUserById
method deletes a user by id.
Finally, we'll need to create a controller. A controller is a class that contains methods that handle HTTP requests. We can create a controller by annotating a class with the @RestController
annotation.
@RestController
@RequestMapping("/users")
class UserController(
private val userService: UserService
) {
@PostMapping
fun createUser(@RequestBody user: User): User {
return userService.createUser(user)
}
@GetMapping("/{id}")
fun getUserById(@PathVariable id: Long): User? {
return userService.getUserById(id)
}
@GetMapping
fun getAllUsers(): List<User> {
return userService.getAllUsers()
}
@PutMapping
fun updateUser(@RequestBody user: User): User {
return userService.updateUser(user)
}
@DeleteMapping("/{id}")
fun deleteUserById(@PathVariable id: Long) {
userService.deleteUserById(id)
}
}
The @RestController
annotation indicates that this is a controller. The @RequestMapping
annotation maps HTTP requests to methods in the controller. The @PostMapping
annotation maps HTTP POST requests to the createUser
method. The @GetMapping
annotation maps HTTP GET requests to the getUserById
method. The @PutMapping
annotation maps HTTP PUT requests to the updateUser
method. The @DeleteMapping
annotation maps HTTP DELETE requests to the deleteUserById
method.
We can test the endpoints using curl or Postman.
$ curl -X POST localhost:8080/users -d '{"name": "John Doe", "age": 42}' -H "Content-Type: application/json"
{"id":1,"name":"John Doe","age":42}
$ curl localhost:8080/users/1
{"id":1,"name":"John Doe","age":42}
$ curl localhost:8080/users
[{"id":1,"name":"John Doe","age":42}]
$ curl -X PUT localhost:8080/users -d '{"id": 1, "name": "Jane Doe", "age": 43}' -H "Content-Type: application/json"
{"id":1,"name":"Jane Doe","age":43}
$ curl -X DELETE localhost:8080/users/1
In this article, we've seen how to use Kotlin and Spring Data to connect to a database.