Kotlin + Quarkus + MyBatis - Build REST CRUD API example
Hello everyone. Today we will learn how to develop REST-style CRUD APIs with Kotlin, Quarkus, MyBatis, and H2 Database. You can download the source code from our Github repository.
Quarkus is a Java framework designed to run within containers. Fixating on expeditious start-up times and low memory utilization makes it more felicitous to run within container orchestration platforms like Kubernetes.Quarkus supports many industry-standard libraries such as Hibernate, Kubernetes, RESTEasy, Eclipse MicroProfile, and more...
MyBatis is an open-source persistence framework that simplifies the implementation of database access in Java applications. It provides support for custom SQL, stored procedures, and different types of mapping relations. Simply put, it's an alternative to JDBC and Hibernate.
After completing this tutorial what we will build?
We will build REST API CRUD features:
- GET - Fetch all User : /api/v1/users
- GET - Get User by ID : /api/v1/users/{id}
- POST - Create User : /api/v1/users
- PUT - Edit User Details : /api/v1/users/
- DELETE - Delete User : /api/v1/users/{id}
Technologies used:
- Quarkus 2.2.3.Final
- MyBatis 0.0.9
- Kotlin
- Gradle
- H2DB
Project Directory:
Gradle Build(build.gradle.kts):
import org.jetbrains.kotlin.gradle.tasks.KotlinCompileplugins {javaid("io.quarkus")kotlin("jvm") version "1.5.31"}repositories {mavenCentral()mavenLocal()}val quarkusPlatformGroupId: String by projectval quarkusPlatformArtifactId: String by projectval quarkusPlatformVersion: String by projectdependencies {implementation(enforcedPlatform("${quarkusPlatformGroupId}:${quarkusPlatformArtifactId}:${quarkusPlatformVersion}"))implementation("io.quarkus:quarkus-arc")implementation("io.quarkus:quarkus-resteasy-jsonb")implementation("io.quarkiverse.mybatis:quarkus-mybatis:0.0.9")implementation("io.quarkus:quarkus-jdbc-h2")testImplementation("io.quarkus:quarkus-junit5")testImplementation("io.rest-assured:rest-assured")implementation(kotlin("stdlib-jdk8"))}group = "com.knf.dev.demo"version = "1.0.0-SNAPSHOT"java {sourceCompatibility = JavaVersion.VERSION_11targetCompatibility = JavaVersion.VERSION_11}tasks.withType<JavaCompile> {options.encoding = "UTF-8"options.compilerArgs.add("-parameters")}val compileKotlin: KotlinCompile by taskscompileKotlin.kotlinOptions {jvmTarget = "11"}val compileTestKotlin: KotlinCompile by taskscompileTestKotlin.kotlinOptions {jvmTarget = "11"}
Database Setup [schema.sql]:
We will create a table called users with a few simple columns. We can initialize a schema by creating a schema.sql file in the resources.
create table users(id integer not null,firstName varchar(255) not null,lastName varchar(255) not null,emailId varchar(255) not null,primary key(id));
application.properties:
quarkus.datasource.db-kind = h2
quarkus.datasource.username = sa
# quarkus.datasource.password =
quarkus.datasource.jdbc.url = jdbc:h2:mem:test
quarkus.mybatis.initial-sql=schema.sql
Create User Model [User.kt]:
package com.knf.dev.demo.model
class User {
var id: Long = 0
var firstName: String? = null
var lastName: String? = null
var emailId: String? = null
constructor() {}
constructor(id: Long, firstName: String?,
lastName: String?, emailId: String?) : super() {
this.id = id
this.firstName = firstName
this.lastName = lastName
this.emailId = emailId
}
}
Create User Repository [UserRepository.kt]:
package com.knf.dev.demo.repositoryimport com.knf.dev.demo.model.Userimport org.apache.ibatis.annotations.*@Mapperinterface UserRepository {@Select("select * from users")fun findAll(): List<User?>?@Select("SELECT * FROM users WHERE id = #{id}")fun findById(id: Long): User?@Delete("DELETE FROM users WHERE id = #{id}")fun deleteById(id: Long): Int@Insert("INSERT INTO users(id, firstName, lastName,emailId) " +" VALUES (#{id}, #{firstName}, #{lastName}, #{emailId})")fun insert(user: User?): Int@Update("Update users set firstName=#{firstName}, " +" lastName=#{lastName}, emailId=#{emailId} where id=#{id}")fun update(user: User?): Int}
UserController.kt:
package com.knf.dev.demo.controllerimport com.knf.dev.demo.model.Userimport com.knf.dev.demo.repository.UserRepositoryimport javax.inject.Injectimport javax.ws.rs.*import javax.ws.rs.core.MediaType@Path("/api/users")class UserController {@Injectvar userRepository: UserRepository? = null@GET@Produces(MediaType.APPLICATION_JSON)fun getUsers(): kotlin.collections.List<User?>? {return userRepository!!.findAll()}@GET@Path("/{id}")@Produces(MediaType.APPLICATION_JSON)fun getUser(@PathParam("id") id: Long?): User? {return userRepository!!.findById(id!!)}@PUT@Consumes(MediaType.APPLICATION_JSON)fun updateUser(user: User?) {userRepository!!.update(user)}@POST@Produces(MediaType.APPLICATION_JSON)@Consumes(MediaType.APPLICATION_JSON)fun addUser(user: User?) {userRepository!!.insert(user)}@DELETE@Path("/{id}")fun deleteUser(@PathParam("id") id: Long?) {userRepository!!.deleteById(id!!)}}
More Quarkus Related topics,
- QUARKUS + Hibernate CRUD example - Creating a CRUD REST API/Service
- Build REST CRUD APIs with Quarkus and MyBatis
- Kotlin + Quarkus + Hibernate - Build REST CRUD API example
- Create Quarkus Project With code.quarkus.io: Hello world example
- Quarkus - How to send email via SMTP - Quickstart
- Quarkus - Qute - Hello World Example
- Quarkus + Maven Hello World Example
- Configuring the HTTP Port on Quarkus Applications
- Quarkus - Interview questions and answers