在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称(OpenSource Name):seratch/kotliquery开源软件地址(OpenSource Url):https://github.com/seratch/kotliquery开源编程语言(OpenSource Language):Kotlin 99.9%开源软件介绍(OpenSource Introduction):KotliQueryKotliQuery is a handy RDB client library for Kotlin developers! The design is highly inspired by ScalikeJDBC, which is a proven database library in Scala. The priorities in this project are:
This library simply mitigates some pain points of the JDBC but our goal is not to completely encapsulate it. Getting StartedThe quickest way to try this library out would be to start with a simple Gradle project. You can find some examples here. build.gradleapply plugin: 'kotlin'
buildscript {
ext.kotlin_version = '1.6.21'
repositories {
mavenCentral()
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
repositories {
mavenCentral()
}
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'com.github.seratch:kotliquery:1.8.0'
implementation 'com.h2database:h2:2.1.210'
} ExampleKotliQuery is much more easy-to-use than you expect. After just reading this short section, you will have learnt enough. Creating DB SessionFirst thing you do is to create a import kotliquery.*
val session = sessionOf("jdbc:h2:mem:hello", "user", "pass") HikariCPFor production-grade applications, utilizing a connection pool library for better performance and resource management is highly recommended. KotliQuery provides an out-of-the-box solution that leverages HikariCP, which is a widely accepted connection pool library. HikariCP.default("jdbc:h2:mem:hello", "user", "pass")
using(sessionOf(HikariCP.dataSource())) { session ->
// working with the session
} DDL ExecutionYou can use a session for executing both DDLs and DMLs. The session.run(queryOf("""
create table members (
id serial not null primary key,
name varchar(64),
created_at timestamp not null
)
""").asExecute) // returns Boolean Update OperationsUsing val insertQuery: String = "insert into members (name, created_at) values (?, ?)"
session.run(queryOf(insertQuery, "Alice", Date()).asUpdate) // returns effected row count
session.run(queryOf(insertQuery, "Bob", Date()).asUpdate) Select QueriesNow that you've got a database table named
The following query returns a list of all member's IDs. In this line, the SQL statement is not yet executed. Also, this object val allIdsQuery = queryOf("select id from members").map { row -> row.int("id") }.asList With a valid session object, you can perform the SQL statement. The type of returned val ids: List<Int> = session.run(allIdsQuery) As you see, the extractor function is greatly flexible. You can define functions with any return type. All you need to do is to implement a function that extracts values from JDBC data class Member(
val id: Int,
val name: String?,
val createdAt: java.time.ZonedDateTime)
val toMember: (Row) -> Member = { row ->
Member(
row.int("id"),
row.stringOrNull("name"),
row.zonedDateTime("created_at")
)
}
val allMembersQuery = queryOf("select id, name, created_at from members").map(toMember).asList
val members: List<Member> = session.run(allMembersQuery) If you are sure that a query can return zero or one row, val aliceQuery = queryOf("select id, name, created_at from members where name = ?", "Alice").map(toMember).asSingle
val alice: Member? = session.run(aliceQuery) Technically, it's also possible to use // Session object constructor
val session = Session(HikariCP.dataSource(), strict = true)
// an auto-closing code block for session
using(sessionOf(HikariCP.dataSource(), strict = true)) { session ->
} Named query parametersAn alternative way to bind parameters is to use named parameters that start with queryOf(
"""
select id, name, created_at
from members
where (name = :name) and (age = :age)
""",
mapOf("name" to "Alice", "age" to 20)
) Performance-wise, the named parameter syntax can be slightly slower for parsing the statement plus a tiny bit more memory-consuming. But for most use case, the overhead should be ignorable. If you would like to make your SQL statements more readable and/or if your query has to repeat the same parameter in a query, using named query parameters should improve your productivity and the maintainability of the query a lot. Typed paramsYou can specify the Java type for each parameter in the following way. Passing the class val param = Parameter(param, String::class.java)
queryOf("""select id, name
from members
where ? is null or ? = name""",
param, param) As a handier way, you can use the following helper method. queryOf("""select id, name
from members
where ? is null or ? = name""",
null.param<String>(), null.param<String>()) This functionality is particularly useful in the situations like the ones dsecribed here. Working with Large DatasetThe session.forEach(queryOf("select id from members")) { row ->
// working with large data set
}) TransactionRunning queries in a transaction is of course supported! The session.transaction { tx ->
// begin
tx.run(queryOf("insert into members (name, created_at) values (?, ?)", "Alice", Date()).asUpdate)
}
// commit
session.transaction { tx ->
// begin
tx.run(queryOf("update members set name = ? where id = ?", "Chris", 1).asUpdate)
throw RuntimeException() // rollback
} As this library is a bit opinionated, transactions are available only with a code block. We intentionally do not support LicenseThe MIT License Copyright (c) 2015 - Kazuhiro Sera |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论