English | 简体中文

api-docs / org.ktorm.dsl / Query / <init>

<init>

Query(database: Database, expression: QueryExpression)

Query is an abstraction of query operations and the core class of Ktorm’s query DSL.

The constructor of this class accepts two parameters: database is the database instance that this query
is running on; expression is the abstract representation of the executing SQL statement. Usually, we don’t
use the constructor to create Query objects but use the database.from(..).select(..) syntax instead.

Query provides a built-in iterator, so we can iterate the results by a for-each loop:

for (row in database.from(Employees).select()) {
println(row[Employees.name])
}

Moreover, there are many extension functions that can help us easily process the query results, such as
Query.map, Query.flatMap, Query.associate, Query.fold, etc. With the help of these functions, we can
obtain rows from a query just like it’s a common Kotlin collection.

Query objects are immutable. Query DSL functions are provided as its extension functions normally. We can
call these functions in chaining style to modify them and create new query objects. Here is a simple example:

val query = database
.from(Employees)
.select(Employees.salary)
.where { (Employees.departmentId eq 1) and (Employees.name like "%vince%") }

Easy to know that the query obtains the salary of an employee named vince in department 1. The generated
SQL is obviously:

select t_employee.salary as t_employee_salary
from t_employee
where (t_employee.department_id = ?) and (t_employee.name like ?)

More usages can be found in the documentations of those DSL functions.