Kotlin + Quarkus + Hibernate - Build REST CRUD API example

Hello everyone, today we will learn how to build RESTful API using KotlinQuarkus, and Hibernate with the help of one simple example. 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...

It uses JAX-RS for the REST endpoints, JPA to preserve data models, and CDI for dependency injections. 

Let's start to build RESTful API with QUARKUS


 Technologies used:

  • Quarkus 2.2.3.Final
  • Hibernate 5.5.7.Final
  • H2 Database
  • Kotlin

Project Structure:


Gradle Build(build.gradle.kts):

import org.jetbrains.kotlin.gradle.tasks.KotlinCompile

plugins {
java
id("io.quarkus")
kotlin("jvm") version "1.5.31"
}

repositories {
mavenCentral()
mavenLocal()
}

val quarkusPlatformGroupId: String by project
val quarkusPlatformArtifactId: String by project
val quarkusPlatformVersion: String by project

dependencies {
implementation(enforcedPlatform(
"${quarkusPlatformGroupId}:${quarkusPlatformArtifactId}:
     ${quarkusPlatformVersion}"))

implementation("io.quarkus:quarkus-arc")
implementation("io.quarkus:quarkus-resteasy-jsonb")
implementation("io.quarkus:quarkus-hibernate-orm")
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_11
targetCompatibility = JavaVersion.VERSION_11
}

tasks.withType<JavaCompile> {
options.encoding = "UTF-8"
options.compilerArgs.add("-parameters")
}
val compileKotlin: KotlinCompile by tasks
compileKotlin.kotlinOptions {
jvmTarget = "11"
}
val compileTestKotlin: KotlinCompile by tasks
compileTestKotlin.kotlinOptions {
jvmTarget = "11"
}

application.properties

# datasource configuration
quarkus.datasource.db-kind = h2
quarkus.datasource.username = sa
# quarkus.datasource.password =
quarkus.datasource.jdbc.url = jdbc:h2:mem:test

# drop and create the database at startup
quarkus.hibernate-orm.database.generation=drop-and-create
#quarkus.hibernate-orm.sql-load-script = data.sql

Entity class(User.kt) - ORM

package com.knf.dev.demo.entity

import java.io.Serializable
import javax.persistence.*

@Table(name = "users")
@Entity
class User : Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
var id: Long? = null
var firstName: String? = null
var lastName: String? = null
var emailId: String? = null

constructor(id: Long?, firstName: String?,
         lastName: String?, emailId: String?) : super() {

this.id = id
this.firstName = firstName
this.lastName = lastName
this.emailId = emailId
}
constructor() : super() {}
}

UserService.kt

package com.knf.dev.demo.service
import com.knf.dev.demo.entity.User
import javax.inject.Inject
import javax.inject.Singleton
import javax.persistence.EntityManager
import javax.transaction.Transactional

@Singleton
class UserService {
@Inject
var entityManager: EntityManager? = null

fun getUsers(): kotlin.collections.List<User?>? {
return entityManager!!.
createQuery("SELECT c FROM User c").
resultList as List<User?>?
}

fun getUser(id: Long?): User {
return entityManager!!.find(User::class.java, id)
}

@Transactional(Transactional.TxType.REQUIRED)
fun addUser(user: User?): User? {
entityManager!!.persist(user)
return user
}

@Transactional(Transactional.TxType.REQUIRED)
fun updateUser(id: Long?, user: User) {
val userToUpdate: User = entityManager!!.
find(User::class.java, id)
if (null != userToUpdate) {
userToUpdate.firstName = user.firstName
userToUpdate.lastName = user.lastName
userToUpdate.emailId = user.emailId
} else {
throw RuntimeException("No such user available")
}
}

@Transactional(Transactional.TxType.REQUIRED)
fun deleteUser(id: Long?) {
val user: User = getUser(id)
entityManager!!.remove(user)
}
}

UserController.kt

package com.knf.dev.demo.controller
import com.knf.dev.demo.entity.User
import com.knf.dev.demo.service.UserService
import javax.inject.Inject
import javax.ws.rs.*
import javax.ws.rs.core.MediaType

@Path("/api/users")
class UserController {
@Inject
var userResource: UserService? = null

@GET
@Produces(MediaType.APPLICATION_JSON)
fun getUsers(): kotlin.collections.List<User?>? {
return userResource?.getUsers()
}

@GET
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
fun getUser(@PathParam("id") id: Long?): User? {
return userResource?.getUser(id)
}

@PUT
@Path("/{id}")
@Consumes(MediaType.APPLICATION_JSON)
fun updateUser(@PathParam("id") id: Long?, user: User?) {
userResource?.updateUser(id, user!!)
}

@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
fun addUser(user: User?): User? {
return userResource?.addUser(user)
}

@DELETE
@Path("/{id}")
fun deleteUser(@PathParam("id") id: Long?) {
userResource?.deleteUser(id)
}
}

Verify REST APIs

Build application jar file:
gradle build


Start the application: 
java -jar quarkus-run.jar


1. Add user


 2. Update user


3. Delete user

 

4. Get all users

 


5. Get single user



More Quarkus Related topics,

Popular posts from this blog

Spring boot video streaming example-HTML5

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Spring Boot + Mockito simple application with 100% code coverage

Spring Boot + OpenCSV Export Data to CSV Example

Custom Exception Handling in Quarkus REST API

DataTable-Pagination example with Spring boot, jQuery and ajax

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Node JS mini projects with source code - free download

Spring boot web project free download:User Registration System

Java - Blowfish Encryption and decryption Example