PostgreSQL
suggest changePostgreSQL is a powerful, open-source object-relational database system known for reliability, feature richness, and performance. In Kotlin backend development (such as Ktor, Spring Boot, or standalone microservices), you can interact with PostgreSQL using:
- Direct JDBC with HikariCP: Fast, lightweight connection pooling and standard SQL queries.
- JetBrains Exposed: The idiomatic, type-safe SQL library created by JetBrains specifically for Kotlin.
Dependencies (build.gradle.kts)
Add the PostgreSQL JDBC driver, HikariCP connection pool, and JetBrains Exposed to your build configuration:
dependencies {
// PostgreSQL JDBC Driver
implementation("org.postgresql:postgresql:42.7.14")
// HikariCP connection pool
implementation("com.zaxxer:HikariCP:7.1.0")
// JetBrains Exposed (Core, DAO, JDBC, java.time and JSON extensions)
val exposedVersion = "1.6.0"
implementation("org.jetbrains.exposed:exposed-core:$exposedVersion")
implementation("org.jetbrains.exposed:exposed-dao:$exposedVersion")
implementation("org.jetbrains.exposed:exposed-jdbc:$exposedVersion")
implementation("org.jetbrains.exposed:exposed-java-time:$exposedVersion")
implementation("org.jetbrains.exposed:exposed-json:$exposedVersion")
}
Direct JDBC with HikariCP Connection Pooling
HikariCP is the de facto standard connection pool on the JVM due to its exceptional performance and low resource overhead.
import com.zaxxer.hikari.HikariConfig
import com.zaxxer.hikari.HikariDataSource
import java.sql.ResultSet
data class User(val id: Long, val username: String, val email: String)
class DatabaseService {
private val dataSource: HikariDataSource
init {
val config = HikariConfig().apply {
jdbcUrl = "jdbc:postgresql://localhost:5432/myapp_db"
username = "postgres"
password = "secretpassword"
maximumPoolSize = 10
isAutoCommit = false
addDataSourceProperty("cachePrepStmts", "true")
addDataSourceProperty("prepStmtCacheSize", "250")
}
dataSource = HikariDataSource(config)
}
fun createUser(username: String, email: String): Long {
val sql = "INSERT INTO users (username, email) VALUES (?, ?) RETURNING id"
return dataSource.connection.use { conn ->
conn.prepareStatement(sql).use { stmt ->
stmt.setString(1, username)
stmt.setString(2, email)
val rs = stmt.executeQuery()
if (rs.next()) rs.getLong("id") else throw IllegalStateException("Insert failed")
}.also {
conn.commit()
}
}
}
fun findUserById(id: Long): User? {
val sql = "SELECT id, username, email FROM users WHERE id = ?"
return dataSource.connection.use { conn ->
conn.prepareStatement(sql).use { stmt ->
stmt.setLong(1, id)
stmt.executeQuery().use { rs ->
if (rs.next()) rs.toUser() else null
}
}
}
}
private fun ResultSet.toUser() = User(
id = getLong("id"),
username = getString("username"),
email = getString("email")
)
fun close() = dataSource.close()
}
JetBrains Exposed (Type-Safe DSL)
Exposed provides an idiomatic Kotlin DSL that translates Kotlin expressions into parameterized SQL queries.
Defining Tables
import org.jetbrains.exposed.v1.core.Table
import org.jetbrains.exposed.v1.javatime.CurrentTimestamp
import org.jetbrains.exposed.v1.javatime.timestamp
object Users : Table("users") {
val id = long("id").autoIncrement()
val username = varchar("username", length = 50).uniqueIndex()
val email = varchar("email", length = 100)
val createdAt = timestamp("created_at").defaultExpression(CurrentTimestamp)
override val primaryKey = PrimaryKey(id)
}
Performing Database Operations
import org.jetbrains.exposed.v1.core.*
import org.jetbrains.exposed.v1.jdbc.*
import org.jetbrains.exposed.v1.jdbc.transactions.transaction
fun main() {
// Initialize Database connection via HikariCP or JDBC URL
Database.connect(
url = "jdbc:postgresql://localhost:5432/myapp_db",
driver = "org.postgresql.Driver",
user = "postgres",
password = "secretpassword"
)
// All queries must execute inside a transaction block
transaction {
// Create table schema if it does not exist
SchemaUtils.create(Users)
// Insert records
val userId = Users.insert {
it[username] = "john_doe"
it[email] = "john@example.com"
} get Users.id
println("Inserted user with ID: $userId")
// Query records
val users = Users.selectAll()
.where { Users.username eq "john_doe" }
.map { row ->
User(
id = row[Users.id],
username = row[Users.username],
email = row[Users.email]
)
}
println("Found users: $users")
// Update records
Users.update({ Users.id eq userId }) {
it[email] = "new_email@example.com"
}
// Delete records
Users.deleteWhere { Users.id eq userId }
}
}
Working with PostgreSQL Native Types
UUID Primary Keys
PostgreSQL has built-in support for native uuid columns:
import org.jetbrains.exposed.v1.core.Table
import org.jetbrains.exposed.v1.core.java.javaUUID
import java.util.UUID
object Tenants : Table("tenants") {
val id = javaUUID("id").clientDefault { UUID.randomUUID() }
val name = varchar("name", 100)
override val primaryKey = PrimaryKey(id)
}
JSON / JSONB Columns
PostgreSQL's jsonb column format provides efficient querying over unstructured documents. In Exposed (@Serializable requires the kotlin("plugin.serialization") Gradle plugin):
import org.jetbrains.exposed.v1.core.Table
import org.jetbrains.exposed.v1.json.jsonb
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
@Serializable
data class UserSettings(val theme: String, val notificationsEnabled: Boolean)
object Profiles : Table("profiles") {
val id = long("id").autoIncrement()
val settings = jsonb<UserSettings>("settings", Json.Default)
override val primaryKey = PrimaryKey(id)
}
Best Practices
- Always use connection pooling: Never call
DriverManager.getConnection()per HTTP request. Always pool connections using HikariCP. - Never interpolate raw strings into queries: Always use parameterized queries or Exposed DSL to prevent SQL injection.
- Configure connection pool limits properly: Set maximum pool size based on PostgreSQL server resources (
max_connections) and worker threads, typically between 10 and 20 for web services. - Manage transaction boundaries: Keep transactions as short as possible to prevent connection starvation and lock contention.