English | 简体中文

api-docs / me.liuwj.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://ktorm.liuwj.me/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 by int("id").primaryKey()
val name by varchar("name")
val job by varchar("job")
val hireDate by 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

Types

NameSummary

ColumnRegistration

inner class ColumnRegistration<C : Any, E : Any> : 
    ReadOnlyProperty<BaseTable<E>, Column<C>>

Wrap a new registered column, providing more operations, such as configure a binding, mark it as
the primary key, and so on.

Constructors

NameSummary

<init>

BaseTable(
    tableName: String,
    alias: 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.

columns

val columns: List<Column<*>>

Return all columns of the table.

entityClass

val entityClass: KClass<E>?

The entity class this table is bound to.

primaryKey

val primaryKey: Column<*>?

The primary key column of this table.

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.

createEntityWithoutReferences

fun createEntityWithoutReferences(row: QueryRowSet): E

Create an entity object from the specific row without obtaining referenced entities’ data automatically.

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

Mark the registered column as the primary key.

registerColumn

fun <C : Any> registerColumn(
    name: String,
    sqlType: SqlType<C>
): BaseTable.ColumnRegistration<C, E>

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> BaseTable.ColumnRegistration<C, E>.transform(
    fromUnderlyingValue: (C) -> R,
    toUnderlyingValue: (R) -> C
): BaseTable.ColumnRegistration<R, E>

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(): EntitySequence<E, T>

Create an EntitySequence, auto left joining all the reference tables.

asSequenceWithoutReferences

fun <E : Any, T : BaseTable<E>> T.asSequenceWithoutReferences(): EntitySequence<E, T>

Create an EntitySequence without left joining reference tables.

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 <E : Any> BaseTable<E>.blob(
    name: String
): BaseTable.ColumnRegistration<ByteArray, E>

Define a column typed of BlobSqlType.

boolean

fun <E : Any> BaseTable<E>.boolean(
    name: String
): BaseTable.ColumnRegistration<Boolean, E>

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.

bytes

fun <E : Any> BaseTable<E>.bytes(
    name: String
): BaseTable.ColumnRegistration<ByteArray, E>

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: QuerySourceExpression,
    on: ColumnDeclaring<Boolean>? = null
): JoinExpression

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

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

date

fun <E : Any> BaseTable<E>.date(
    name: String
): BaseTable.ColumnRegistration<LocalDate, E>

Define a column typed of LocalDateSqlType.

datetime

fun <E : Any> BaseTable<E>.datetime(
    name: String
): BaseTable.ColumnRegistration<LocalDateTime, E>

Define a column typed of LocalDateTimeSqlType.

datetimeoffset

fun <E : Any> BaseTable<E>.datetimeoffset(
    name: String
): BaseTable.ColumnRegistration<DateTimeOffset, E>

Define a column typed of DateTimeOffsetSqlType.

decimal

fun <E : Any> BaseTable<E>.decimal(
    name: String
): BaseTable.ColumnRegistration<BigDecimal, E>

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 <E : Any> BaseTable<E>.double(
    name: String
): BaseTable.ColumnRegistration<Double, E>

Define a column typed of DoubleSqlType.

enum

fun <E : Any, C : Enum<C>> BaseTable<E>.enum(
    name: String,
    typeRef: TypeReference<C>
): BaseTable.ColumnRegistration<C, E>

Define a column typed of EnumSqlType.

findAll

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

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

findById

fun <E : Any> BaseTable<E>.findById(id: Any): E?

Obtain a entity object by its ID, 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.

findListByIds

fun <E : Any> BaseTable<E>.findListByIds(
    ids: Collection<Any>
): List<E>

Obtain a list of entity objects by IDs, auto left joining all the reference tables.

findOne

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

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

float

fun <E : Any> BaseTable<E>.float(
    name: String
): BaseTable.ColumnRegistration<Float, E>

Define a column typed of FloatSqlType.

innerJoin

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

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

Join the right table and return a JoinExpression, 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 <E : Any> BaseTable<E>.int(
    name: String
): BaseTable.ColumnRegistration<Int, E>

Define a column typed of IntSqlType.

jdbcDate

fun <E : Any> BaseTable<E>.jdbcDate(
    name: String
): BaseTable.ColumnRegistration<Date, E>

Define a column typed of DateSqlType.

jdbcTime

fun <E : Any> BaseTable<E>.jdbcTime(
    name: String
): BaseTable.ColumnRegistration<Time, E>

Define a column typed of TimeSqlType.

jdbcTimestamp

fun <E : Any> BaseTable<E>.jdbcTimestamp(
    name: String
): BaseTable.ColumnRegistration<Timestamp, E>

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 <E : Any, C : Any> BaseTable<E>.json(
    name: String,
    typeRef: TypeReference<C>,
    mapper: ObjectMapper = sharedObjectMapper
): BaseTable.ColumnRegistration<C, E>

Define a column typed of JsonSqlType.

leftJoin

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

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

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

long

fun <E : Any> BaseTable<E>.long(
    name: String
): BaseTable.ColumnRegistration<Long, E>

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 <E : Any> BaseTable<E>.monthDay(
    name: String
): BaseTable.ColumnRegistration<MonthDay, E>

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

naturalJoin

fun BaseTable<*>.naturalJoin(
    right: QuerySourceExpression
): NaturalJoinExpression

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

Join the right table and return a NaturalJoinExpression, translated to natural join in MySQL.

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.

rightJoin

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

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

Join the right table and return a JoinExpression, 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.

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 <E : Any> BaseTable<E>.text(
    name: String
): BaseTable.ColumnRegistration<String, E>

Define a column typed of TextSqlType.

time

fun <E : Any> BaseTable<E>.time(
    name: String
): BaseTable.ColumnRegistration<LocalTime, E>

Define a column typed of LocalTimeSqlType.

timestamp

fun <E : Any> BaseTable<E>.timestamp(
    name: String
): BaseTable.ColumnRegistration<Instant, E>

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 <E : Any> BaseTable<E>.uuid(
    name: String
): BaseTable.ColumnRegistration<UUID, E>

Define a column typed of UuidSqlType.

varchar

fun <E : Any> BaseTable<E>.varchar(
    name: String
): BaseTable.ColumnRegistration<String, E>

Define a column typed of VarcharSqlType.

year

fun <E : Any> BaseTable<E>.year(
    name: String
): BaseTable.ColumnRegistration<Year, E>

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

yearMonth

fun <E : Any> BaseTable<E>.yearMonth(
    name: String
): BaseTable.ColumnRegistration<YearMonth, E>

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.