English | 简体中文

api-docs / org.ktorm.schema / BaseTable

BaseTable

abstract class BaseTable<E : Any> : TypeReference<E> (source code)

Base class of Ktorm’s table objects, represents relational tables in the database.

This class provides the basic ability of table and column definition but doesn’t support any binding mechanisms.
If you need the binding support to Entity interfaces, use Table instead.

There is an abstract function doCreateEntity. Subclasses should implement this function, creating an entity object
from the result set returned by a query, using the binding rules defined by themselves. Here, the type of the entity
object could be an interface extending from Entity, or a data class, POJO, or any kind of classes.

Here is an example defining an entity as data class. The full documentation can be found at:
https://www.ktorm.org/en/define-entities-as-any-kind-of-classes.html

data class Staff(
val id: Int,
val name: String,
val job: String,
val hireDate: LocalDate
)
object Staffs : BaseTable<Staff>("t_employee") {
val id = int("id").primaryKey()
val name = varchar("name")
val job = varchar("job")
val hireDate = date("hire_date")
override fun doCreateEntity(row: QueryRowSet, withReferences: Boolean) = Staff(
id = row[id] ?: 0,
name = row[name].orEmpty(),
job = row[job].orEmpty(),
hireDate = row[hireDate] ?: LocalDate.now()
)
}

Since
2.5

Constructors

NameSummary

<init>

BaseTable(
    tableName: String,
    alias: String? = null,
    catalog: String? = null,
    schema: String? = null,
    entityClass: KClass<E>? = null)

Base class of Ktorm’s table objects, represents relational tables in the database.

Properties

NameSummary

alias

val alias: String?

The table’s alias.

catalog

val catalog: String?

The table’s catalog.

columns

val columns: List<Column<*>>

Return all columns of the table.

entityClass

val entityClass: KClass<E>?

The entity class this table is bound to.

primaryKeys

val primaryKeys: List<Column<*>>

The primary key columns of this table.

schema

val schema: String?

The table’s schema.

tableName

val tableName: String

The table’s name.

Inherited Properties

NameSummary

referencedKotlinType

val referencedKotlinType: KType

The actual kotlin type argument of subclass without erased.

referencedType

val referencedType: Type

The actual type argument of subclass without erased.

Functions

NameSummary

aliased

open fun aliased(alias: String): BaseTable<E>

Return a new-created table object with all properties (including the table name and columns and so on) being
copied from this table, but applying a new alias given by the parameter.

asExpression

fun asExpression(): TableExpression

Convert this table to a TableExpression.

copyDefinitionsFrom

fun copyDefinitionsFrom(src: BaseTable<*>): Unit

Copy column definitions from src to this table.

createEntity

fun createEntity(
    row: QueryRowSet,
    withReferences: Boolean = true
): E

Create an entity object from the specific row of query results. This function uses the binding configurations
of the table, filling column values into corresponding properties of the returned entity.

doCreateEntity

abstract fun doCreateEntity(
    row: QueryRowSet,
    withReferences: Boolean
): E

Create an entity object from the specific row of query results.

equals

fun equals(other: Any?): Boolean

Indicates whether some other object is “equal to” this table.
Two tables are equal only if they are the same instance.

get

operator fun get(name: String): Column<*>

Obtain a column from this table by the name.

hashCode

fun hashCode(): Int

Return a hash code value for this table.

primaryKey

fun <C : Any> Column<C>.primaryKey(): Column<C>

Mark the registered column as a primary key.

registerColumn

fun <C : Any> registerColumn(
    name: String,
    sqlType: SqlType<C>
): Column<C>

Register a column to this table with the given name and sqlType.

toString

open fun toString(): String

Return a string representation of this table.

transform

fun <C : Any, R : Any> Column<C>.transform(
    fromUnderlyingValue: (C) -> R,
    toUnderlyingValue: (R) -> C
): Column<R>

Transform the registered column’s SqlType to another. The transformed SqlType has the same typeCode and
typeName as the underlying one, and performs the specific transformations on column values.

Extension Functions

NameSummary

all

fun <E : Any, T : BaseTable<E>> T.all(
    predicate: (T) -> ColumnDeclaring<Boolean>
): Boolean

Check if all the records in the table matches the given predicate.

any

fun <E : Any, T : BaseTable<E>> T.any(): Boolean

Check if there is any record in the table.

fun <E : Any, T : BaseTable<E>> T.any(
    predicate: (T) -> ColumnDeclaring<Boolean>
): Boolean

Check if there is any record in the table matches the given predicate.

asSequence

fun <E : Any, T : BaseTable<E>> T.asSequence(
    withReferences: Boolean = true
): EntitySequence<E, T>

Create an EntitySequence from this table.

averageBy

fun <E : Any, T : BaseTable<E>> T.averageBy(
    selector: (T) -> ColumnDeclaring<out Number>
): Double?

Return the average value of the given column or expression of all the records, null if there are no records.

batchInsert

fun <T : BaseTable<*>> T.batchInsert(
    block: BatchInsertStatementBuilder<T>.() -> Unit
): IntArray

Construct insert expressions in the given closure, then batch execute them and return the effected
row counts for each expression.

batchUpdate

fun <T : BaseTable<*>> T.batchUpdate(
    block: BatchUpdateStatementBuilder<T>.() -> Unit
): IntArray

Construct update expressions in the given closure, then batch execute them and return the effected
row counts for each expression.

blob

fun BaseTable<*>.blob(name: String): Column<ByteArray>

Define a column typed of BlobSqlType.

boolean

fun BaseTable<*>.boolean(name: String): Column<Boolean>

Define a column typed of BooleanSqlType.

bulkInsert

fun <T : BaseTable<*>> T.bulkInsert(
    block: BulkInsertStatementBuilder<T>.() -> Unit
): Int

Construct a bulk insert expression in the given closure, then execute it and return the effected row count.

bulkInsert

fun <T : BaseTable<*>> T.bulkInsert(
    block: BulkInsertStatementBuilder<T>.(T) -> Unit
): Int

Construct a bulk insert expression in the given closure, then execute it and return the
effected row count.

bulkInsertOrUpdate

fun <T : BaseTable<*>> T.bulkInsertOrUpdate(
    block: BulkInsertOrUpdateStatementBuilder<T>.() -> Unit
): Int

Bulk insert records to the table, determining if there is a key conflict while inserting each of them,
and automatically performs updates if any conflict exists.

bulkInsertOrUpdate

fun <T : BaseTable<*>> T.bulkInsertOrUpdate(
    block: BulkInsertOrUpdateStatementBuilder<T>.(T) -> Unit
): Int

Bulk insert records to the table, determining if there is a key conflict while inserting each of them,
and automatically performs updates if any conflict exists.

bytes

fun BaseTable<*>.bytes(name: String): Column<ByteArray>

Define a column typed of BytesSqlType.

count

fun <E : Any, T : BaseTable<E>> T.count(): Int

Return the records count in the table.

fun <E : Any, T : BaseTable<E>> T.count(
    predicate: (T) -> ColumnDeclaring<Boolean>
): Int

Return the records count in the table that matches the given predicate.

crossJoin

fun BaseTable<*>.crossJoin(
    right: BaseTable<*>,
    on: ColumnDeclaring<Boolean>? = null
): QuerySource

Join the right table and return a new QuerySource, translated to cross join in SQL.

cube

fun BaseTable<*>.cube(name: String): Column<Cube>

Define a column typed CubeSqlType.

date

fun BaseTable<*>.date(name: String): Column<LocalDate>

Define a column typed of LocalDateSqlType.

datetime

fun BaseTable<*>.datetime(
    name: String
): Column<LocalDateTime>

Define a column typed of LocalDateTimeSqlType.

datetimeoffset

fun BaseTable<*>.datetimeoffset(
    name: String
): Column<OffsetDateTime>

Define a column typed of DateTimeOffsetSqlType.

decimal

fun BaseTable<*>.decimal(name: String): Column<BigDecimal>

Define a column typed of DecimalSqlType.

delete

fun <T : BaseTable<*>> T.delete(
    predicate: (T) -> ColumnDeclaring<Boolean>
): Int

Delete the records in the table that matches the given predicate.

deleteAll

fun BaseTable<*>.deleteAll(): Int

Delete all the records in the table.

double

fun BaseTable<*>.double(name: String): Column<Double>

Define a column typed of DoubleSqlType.

earth

fun BaseTable<*>.earth(name: String): Column<Earth>

Define a column typed EarthSqlType.

enum

fun <C : Enum<C>> BaseTable<*>.enum(name: String): Column<C>

Define a column typed of EnumSqlType.

eq

infix fun <T : Any> T.eq(
    expr: ColumnDeclaring<T>
): BinaryExpression<Boolean>

Equal operator, translated to = in SQL.

findAll

fun <E : Any> BaseTable<E>.findAll(): List<E>

Obtain all the entity objects from this table, auto left joining all the reference tables.

findList

fun <E : Any, T : BaseTable<E>> T.findList(
    predicate: (T) -> ColumnDeclaring<Boolean>
): List<E>

Obtain a list of entity objects matching the given predicate, auto left joining all the reference tables.

findOne

fun <E : Any, T : BaseTable<E>> T.findOne(
    predicate: (T) -> ColumnDeclaring<Boolean>
): E?

Obtain an entity object matching the given predicate, auto left joining all the reference tables.

float

fun BaseTable<*>.float(name: String): Column<Float>

Define a column typed of FloatSqlType.

hstore

fun BaseTable<*>.hstore(name: String): Column<HStore>

Define a column typed HStoreSqlType.

innerJoin

fun BaseTable<*>.innerJoin(
    right: BaseTable<*>,
    on: ColumnDeclaring<Boolean>? = null
): QuerySource

Join the right table and return a new QuerySource, translated to inner join in SQL.

insert

fun <T : BaseTable<*>> T.insert(
    block: AssignmentsBuilder.(T) -> Unit
): Int

Construct an insert expression in the given closure, then execute it and return the effected row count.

insertAndGenerateKey

fun <T : BaseTable<*>> T.insertAndGenerateKey(
    block: AssignmentsBuilder.(T) -> Unit
): Any

Construct an insert expression in the given closure, then execute it and return the auto-generated key.

insertOrUpdate

fun <T : BaseTable<*>> T.insertOrUpdate(
    block: InsertOrUpdateStatementBuilder.(T) -> Unit
): Int

Insert a record to the table, determining if there is a key conflict while it’s being inserted, and automatically
performs an update if any conflict exists.

insertOrUpdate

fun <T : BaseTable<*>> T.insertOrUpdate(
    block: InsertOrUpdateStatementBuilder.(T) -> Unit
): Int

Insert a record to the table, determining if there is a key conflict while it’s being inserted, and automatically
performs an update if any conflict exists.

int

fun BaseTable<*>.int(name: String): Column<Int>

Define a column typed of IntSqlType.

isEmpty

fun <E : Any, T : BaseTable<E>> T.isEmpty(): Boolean

Return true if the table has no records.

isNotEmpty

fun <E : Any, T : BaseTable<E>> T.isNotEmpty(): Boolean

Return true if the table has at lease one record.

jdbcDate

fun BaseTable<*>.jdbcDate(name: String): Column<Date>

Define a column typed of DateSqlType.

jdbcTime

fun BaseTable<*>.jdbcTime(name: String): Column<Time>

Define a column typed of TimeSqlType.

jdbcTimestamp

fun BaseTable<*>.jdbcTimestamp(
    name: String
): Column<Timestamp>

Define a column typed of TimestampSqlType.

joinReferencesAndSelect

fun BaseTable<*>.joinReferencesAndSelect(): Query

Return a new-created Query object, left joining all the reference tables, and selecting all columns of them.

json

fun <C : Any> BaseTable<*>.json(
    name: String,
    mapper: ObjectMapper = sharedObjectMapper
): Column<C>

Define a column typed of JsonSqlType.

leftJoin

fun BaseTable<*>.leftJoin(
    right: BaseTable<*>,
    on: ColumnDeclaring<Boolean>? = null
): QuerySource

Join the right table and return a new QuerySource, translated to left join in SQL.

long

fun BaseTable<*>.long(name: String): Column<Long>

Define a column typed of LongSqlType.

maxBy

fun <E : Any, T : BaseTable<E>, C : Comparable<C>> T.maxBy(
    selector: (T) -> ColumnDeclaring<C>
): C?

Return the max value of the given column or expression of all the records, null if there are no records in the table.

minBy

fun <E : Any, T : BaseTable<E>, C : Comparable<C>> T.minBy(
    selector: (T) -> ColumnDeclaring<C>
): C?

Return the min value of the given column or expression of all the records, null if there are no records in the table.

monthDay

fun BaseTable<*>.monthDay(name: String): Column<MonthDay>

Define a column typed of MonthDaySqlType, instances of MonthDay are saved as strings in format MM-dd.

naturalJoin

fun BaseTable<*>.naturalJoin(
    right: BaseTable<*>
): QuerySource

Join the right table and return a new QuerySource, translated to natural join in SQL.

neq

infix fun <T : Any> T.neq(
    expr: ColumnDeclaring<T>
): BinaryExpression<Boolean>

Not-equal operator, translated to <> in SQL.

none

fun <E : Any, T : BaseTable<E>> T.none(): Boolean

Return true if there is no records in the table.

fun <E : Any, T : BaseTable<E>> T.none(
    predicate: (T) -> ColumnDeclaring<Boolean>
): Boolean

Return true if there is no records in the table that matches the given predicate.

notEq

infix fun <T : Any> T.notEq(
    expr: ColumnDeclaring<T>
): BinaryExpression<Boolean>

Not-equal operator, translated to <> in SQL.

rightJoin

fun BaseTable<*>.rightJoin(
    right: BaseTable<*>,
    on: ColumnDeclaring<Boolean>? = null
): QuerySource

Join the right table and return a new QuerySource, translated to right join in SQL.

select

fun BaseTable<*>.select(
    columns: Collection<ColumnDeclaring<*>>
): Query

fun BaseTable<*>.select(
    vararg columns: ColumnDeclaring<*>
): Query

Create a query object, selecting the specific columns or expressions from this table.

selectDistinct

fun BaseTable<*>.selectDistinct(
    columns: Collection<ColumnDeclaring<*>>
): Query

fun BaseTable<*>.selectDistinct(
    vararg columns: ColumnDeclaring<*>
): Query

Create a query object, selecting the specific columns or expressions from this table distinctly.

short

fun BaseTable<*>.short(name: String): Column<Short>

Define a column typed of ShortSqlType.

sumBy

fun <E : Any, T : BaseTable<E>, C : Number> T.sumBy(
    selector: (T) -> ColumnDeclaring<C>
): C?

Return the sum of the given column or expression of all the records, null if there are no records in the table.

text

fun BaseTable<*>.text(name: String): Column<String>

Define a column typed of TextSqlType.

textArray

fun BaseTable<*>.textArray(name: String): Column<TextArray>

Define a column typed TextArraySqlType.

time

fun BaseTable<*>.time(name: String): Column<LocalTime>

Define a column typed of LocalTimeSqlType.

timestamp

fun BaseTable<*>.timestamp(name: String): Column<Instant>

Define a column typed of InstantSqlType.

update

fun <T : BaseTable<*>> T.update(
    block: UpdateStatementBuilder.(T) -> Unit
): Int

Construct an update expression in the given closure, then execute it and return the effected row count.

uuid

fun BaseTable<*>.uuid(name: String): Column<UUID>

Define a column typed of UuidSqlType.

varchar

fun BaseTable<*>.varchar(name: String): Column<String>

Define a column typed of VarcharSqlType.

year

fun BaseTable<*>.year(name: String): Column<Year>

Define a column typed of YearSqlType, instances of Year are saved as integers.

yearMonth

fun BaseTable<*>.yearMonth(name: String): Column<YearMonth>

Define a column typed of YearMonthSqlType, instances of YearMonth are saved as strings in format yyyy-MM.

Inheritors

NameSummary

Table

open class Table<E : Entity<E>> : BaseTable<E>

Base class of Ktorm’s table objects. This class extends from BaseTable, additionally providing a binding mechanism
with Entity interfaces based on functions such as bindTo, references.