Ktor Database connection with H2 (Ktor and Exposed)
I am expecting you have setup project and having basic understanding of Ktor as explained in my previous article.
I will use following libraries to setup connection to database using Ktor.
Exposed — Kotlin SQL framework
H2 — Embeddable database
HikariCP — High performance JDBC connection pooling
Jackson — JSON serialization/deserialization
After setting up all the required stuff my gradle file looks like
After installing all the required features from the Ktor my application class looks like
Now we need to create table in my case i created Users table using expose Table class and create a separate data class to describe user, Final class looks like
In DatabaseFactory we need to connect database with hikari configured datasource ,Just to test i manually enter two rows as you can see in the class below
We create another class called UserService to handle the queries related to user.
Now finally to interact with database through endpoint we need to create Rout.
In the rout we have to declare all the rout and what user will get after hitting end point.
In my case when i hit http://0.0.0.0:8080/user/
Hope Everything will work fine :-) , I am not sharing code because this is very basic you must know how to setup everything, to move further with more complex API.
Thank you for reading