Kest

Search

Search the documentation

Data

ORM basics

Entities, @Column options, indexes, generated repositories, derived queries and binding an entity to its datasource.

The ORM is a data mapper: entities are plain classes, there is no persistence context, no dirty checking and no proxies, and saving is explicit. For each entity the processor writes the table metadata, a typed row mapper and the insert and update binders, so nothing on the query path uses reflection.

@Entity("items", connection = "main")
@Index("name")
@Index("sku", "colour", unique = true)                    // a composite unique constraint
data class Item(
    @Id @Generated val id: String? = null,
    @Column(length = 40, comment = "display name") val name: String,
    @Column(precision = 10, scale = 2, default = "0") val price: BigDecimal = BigDecimal.ZERO,
    @Column(type = "text") val notes: String? = null,
    @Column(default = "'draft'", index = true) val status: String = "draft",
    @Unique val sku: String,
    val colour: String = "",
    @Version val version: Long = 0,
)
 
@Repository                                                 // uses connection "main", from the entity
interface ItemRepository : CrudRepository<Item, String> {
    fun findBySku(sku: String): Item?
    fun findByPriceGreaterThanOrderByNameAsc(min: BigDecimal): List<Item>
    fun countByStatus(status: String): Long
}

Inject ItemRepository like any provider; the implementation is generated.

Injecting a repository: @InjectRepository

You do not have to declare a repository interface. Like TypeORM's @InjectRepository(User), ask for the repository of an entity on a data source:

import io.kest.orm.sql.Repository
import io.kest.orm.mongo.MongoRepository
 
@Injectable
class UserService(
    @InjectRepository(User::class, "main") private val users: Repository<User>,                // PostgreSQL or MySQL
    @InjectRepository(AuditEntry::class, "events") private val audit: MongoRepository<AuditEntry>,   // MongoDB
    @InjectRepository(User::class) private val bound: Repository<User>,                          // the entity's own data source
)
TypeData sourcePackage
Repository<T>PostgreSQL, MySQLio.kest.orm.sql
MongoRepository<T>MongoDBio.kest.orm.mongo

The second argument names the data source. Left out, it is the one the entity is bound to with @Entity(connection = "..."), and failing that the application's only connection (or the one called default); with several connections and no binding it is an error that says so. The same entity can be injected from several data sources, each with its own rows. Using the wrong type for a data source (Repository<T> for a MongoDB connection) fails at start with a message naming the connection. The processor checks that the type argument matches the entity.

Both extend EntityRepository<T>, which adds the TypeORM-style finders to the CRUD methods:

users.findBy("colour", "red")                           // rows where a property equals a value
users.findBy(mapOf("colour" to "red", "price" to 20))   // several properties; null matches a missing value
users.findOneBy("email", "a@b.c")
users.findByIds(listOf(1, 2, 3))
users.countBy(mapOf("active" to true)); users.existsBy(mapOf("email" to e)); users.deleteBy(mapOf("active" to false))
users.findPage(orderBy = "name", limit = 20, offset = 40)
val (rows, total) = users.findAndCount(mapOf("active" to true), "name", limit = 20)

Repository<T> adds query("select * from users where age > ?", 30), execute("update ...") and datastore. MongoRepository<T> adds aggregate(pipeline), findRaw(filter) and collection. Soft delete, relations, cascades and transactions work as for generated repositories. Declare an interface with derived queries (@Repository interface ...) when you want methods like findByEmailAndActive; the two styles mix freely.

@Column

OptionMeaning
namecolumn name (default: snake_case of the property)
typethe SQL type written as is: "jsonb", "varchar(40)", "mediumtext". Reading and writing still follow the Kotlin type
lengthVARCHAR(length)
precision, scaleNUMERIC(precision, scale)
nullablefor Java reference types; Kotlin follows T?
unique, indexa unique constraint, a plain index
defaultan SQL expression: "0", "'draft'", "CURRENT_TIMESTAMP"
commentthe column comment (PostgreSQL COMMENT ON, MySQL inline)

Also @Id, @Generated(strategy) (identity, UUID, ObjectId), @Unique, @Version (optimistic locking), @Index(columns..., unique, name) (repeatable). Supported types: String, Int, Long, Short, Boolean, Double, Float, BigDecimal, UUID, Instant, LocalDate, LocalDateTime, ByteArray and enums. On MongoDB name, unique and index apply; the SQL-specific options are ignored.

Not built

TypeORM's insert/update/select: false flags, column transformers, simple-array/simple-json, spatial types, and table inheritance. Put a JSON string in a String column with @Column(type = "jsonb").

Created, updated and deleted dates

@Entity("notes") data class Note(
    @Id @Generated val id: String? = null, val text: String,
    @CreateDate val createdAt: Instant? = null,      // set when first saved
    @UpdateDate val updatedAt: Instant? = null,      // set on every save
    @DeleteDate val deletedAt: Instant? = null,      // soft delete
)

Repositories fill the stamps (an Instant or LocalDateTime, to the millisecond); saving an entity you loaded keeps its created stamp. With a @DeleteDate property (it must be nullable), deleteById, delete, deleteAll and derived deleteBy... stamp the row instead of removing it, and every read skips stamped rows: findById, findAll, count, derived queries, relations, the finders of EntityRepository. Also:

notes.restore(id)                       // clears the stamp
notes.hardDelete(id)                    // really deletes, with the cascades of deleteById
notes.findByIdIncludingDeleted(id); notes.findAllIncludingDeleted()

Raw SQL (@NativeQuery, Repository.query) and findWhere with a hand-built Query through a generated or injected repository are filtered too; raw Datastore calls are not. Tested on PostgreSQL, MySQL and MongoDB.

Connections

Kest.run<AppModule> {
    import(OrmModule.forRoot {
        synchronize = true                         // create missing tables and indexes at start (development)
        postgres("main", url, user, password)
        mysql("reports", url, user, password)
        mongo("events", "mongodb://localhost", database = "events")
    })
}

An entity is bound to its datasource with @Entity(connection = "main"). A @Repository for it, and every relation that points at it, use that connection unless they name another (@Repository("reports")). With no binding the connection called default is used. See Several databases.

Queries

Derived names are translated at build time: findBy, readBy, getBy, queryBy, countBy, existsBy, deleteBy, with And, Or, OrderBy...Asc/Desc, First/Top3, and the operators GreaterThan(Equal), LessThan(Equal), Between, In, NotIn, Like, StartingWith, EndingWith, Containing, IsNull, IsNotNull, True, False, Not. An unknown property is a compile error. Conditions on a related entity use the relation name: findByPlayersName, and several hops findByOrderCustomerName (see Relations).

@NativeQuery("select * from items where name ilike :p") passes SQL through (SQL only), findWhere(Query...) is the escape hatch for dynamic queries.

Guarantees

  • @Unique is enforced by the database: a violating write throws DuplicateKeyException.
  • @Version gives optimistic locking: an update with a stale version throws OptimisticLockException.
  • saveAll is one transaction, batched where the driver allows.
  • Every repository method is atomic; see Transactions for groups of them.

Performance

Against hand-written JDBC on PostgreSQL the ORM was indistinguishable at the resolution measured. See Benchmarks.

Column options like TypeORM

@Entity data class Account(
    @Id @Generated val id: String? = null,
    @Column(select = false) val passwordHash: String? = null,      // not loaded by finders; a null on save keeps the stored value
    @Column(insert = false, default = "'pending'") val status: String? = null,   // left out of INSERT: the database default applies
    @Column(update = false) val createdBy: String? = null,         // never changed after creation
    @Column(transformer = Lowercase::class) val email: String,     // your own conversion
    @Column(type = "simple-array") val tags: List<String> = emptyList(),         // "a,b,c" in a text column; List/Set of String, numbers, UUID, enums
    @Column(type = "simple-json") val prefs: Prefs? = null,        // any value as JSON text
    @Column(type = "jsonb") val payload: String? = null,           // a JSON string in a String property (cast for you on PostgreSQL)
    @Column(type = "jsonb") val settings: Settings? = null,        // or any value, stored as JSON
    val location: Point? = null,                                   // spatial, below
)
 
class Lowercase : ColumnTransformer<String, String> { override fun to(value: String) = value.lowercase(); override fun from(value: String) = value }
  • select = false needs a nullable property (it reads as null). Saving an entity whose value is null leaves the stored value alone, so a loaded-then-saved entity does not wipe it; set it by passing a value.
  • A transformer's to runs when writing, from when reading. Stored types: String, Int, Long, Short, Boolean, Double, Float, BigDecimal, UUID, Instant, LocalDate, LocalDateTime, ByteArray. Null skips it.
  • Queries by derived finder methods on a converted column compare the stored form.
  • Spatial: Point(x, y) and Geometry(wkt) map to POINT / GEOMETRY columns and are converted with ST_GeomFromText / ST_AsText. Tested on MySQL; PostgreSQL needs PostGIS (@Column(type = "geometry")) and is untested. There is no native point type support and no MongoDB mapping.
  • These flags, transformers and the JSON types apply to SQL datastores. MongoDB stores converted values but ignores select, insert and update.

Pagination

Never return a whole table. Ask for one page:

val page: Page<Order> = orders.findAll(PageRequest.of(1, 20, Sort.by("createdAt").descending()))
page.items         // the 20 orders
page.total         // how many exist in all
page.pages         // 8
page.hasNext       // true

Pages count from 1, so page = 1 is the first page. PageRequest.of(page, size, sort); size must be 1 or more.

Repository methods

MethodReturns
findAll(pageable)Page<T>: items, page, size, total, pages, hasNext, hasPrevious
findAll(sort)all rows, ordered
findPage(query, pageable, args...)a page of the rows matching a Query
findSlice(query, pageable, args...)Slice<T>: items and hasNext, no COUNT query (cheaper; for "load more")

Derived finders

Add a Pageable as the last parameter. The return type decides what you get:

interface OrderRepository : CrudRepository<Order, String> {
    fun findByStatus(status: String, pageable: Pageable): Page<Order>            // page + total
    fun findByCustomerId(id: String, pageable: Pageable): Slice<Order>           // no total
    fun findByTotalGreaterThan(min: Long, pageable: Pageable): List<Order>      // just this page's rows
    fun findByStatus(status: String, sort: Sort): List<Order>                    // ordering only
}

The Pageable and Sort are not query arguments: findByStatus(status, pageable) still means status = ?. A page's sort replaces the method's own OrderBy.

What the framework does for you

  • Stable order. The id is always added as the last sort key, so rows that tie on the sort column (many orders in the same second) are never repeated or skipped between pages.
  • Safe sorting. A sort property must be a stored property of the entity; anything else (name; drop table x, a relation, a typo) throws InvalidPagingException, which the HTTP layer answers with 400. Column names come from the entity, never from the request text.
  • No wasted COUNT. A short, non-empty page is the last page, so the total is offset + rows without counting. An empty first page is total 0.
  • Soft-deleted rows (@DeleteDate) are left out of items and totals.
  • Works the same on PostgreSQL, MySQL and MongoDB.

From an HTTP request

@Paged turns ?page=2&size=20&sort=name,-createdAt into a Pageable:

@Controller("/orders")
class OrdersController(private val orders: OrderRepository) {
    @Get fun list(@Paged(defaultSize = 20, maxSize = 100, sortable = ["createdAt", "total"], defaultSort = "-createdAt") page: Pageable): Page<Order> =
        orders.findAll(page)
 
    @Get("/open") fun open(@Paged page: Pageable) = orders.findByStatus("open", page)
}

GET /orders?page=2&size=20&sort=-total returns:

{ "items": [ ... ], "page": 2, "size": 20, "total": 143, "pages": 8, "hasNext": true, "hasPrevious": true }

A page below 1, a size of 0 or above maxSize, a non-number, or a sort outside sortable is a 400 with the reason. Sort syntax: name, -name (descending), name:desc, several joined by commas or repeated.

Limits of page numbers

Offset paging reads and discards the skipped rows, so very deep pages (page 50 000 of a large table) get slow. For feeds that people scroll through, use Slice (no COUNT) or cursor paging.

Cursor (keyset) paging

A cursor says "give me the rows after this one", so every page costs the same however deep you are, and rows added or removed between requests are never repeated or skipped:

var page = orders.findCursor(Query.ALL, sort = "createdAt", descending = true, after = null, size = 50)
page.items            // the first 50
page.nextCursor       // an opaque string, or null on the last page
page = orders.findCursor(Query.ALL, "createdAt", true, page.nextCursor, 50)      // the next 50

Send nextCursor to the client and take it back as ?after=.... The sort property must be a stored property that is never null (the id is added as a tie-breaker). It works on PostgreSQL, MySQL and MongoDB. CursorPage has items, size, nextCursor and hasNext.

Typed queries with paging

orders.queryPage(PageRequest.of(1, 20)) { where(Order::status eq "open") } and querySlice(...) combine the typed query DSL with paging.