Kest

Search

Search the documentation

Data

Relations

One-to-many, many-to-one and many-to-many, with foreign keys or junction tables, cascades, orphan removal, lazy loading, join fetching and filters.

Relations are annotations on a property that is not stored, checked at build time, and loaded only when you ask. They work the same on PostgreSQL, MySQL and MongoDB, and across databases.

Foreign keys

@Entity("teams") data class Team(
    @Id @Generated val id: String? = null, val name: String,
    @OneToMany(Player::class, "teamId") val players: List<Player> = emptyList(),
)
@Entity("players") data class Player(
    @Id @Generated val id: String? = null, val teamId: String, val name: String,
    @ManyToOne(Team::class, "teamId") val team: Team? = null,
    @ManyToMany(Skill::class, through = PlayerSkill::class, joinParent = "playerId", joinChild = "skillId") val skills: List<Skill> = emptyList(),
)

@OneToMany(target, mappedBy): the child's foreign-key property. @ManyToOne(target, joinColumn): this entity's own foreign-key property. @ManyToMany(target, through, joinParent, joinChild): a join entity you declare yourself.

Junction tables

Skip the join entity and let Kest keep the links in a table of its own, like TypeORM's @JoinTable(). It works on all three relation kinds:

@Entity("courses") data class Course(
    @Id @Generated val id: String? = null, val title: String,
    @ManyToMany(Student::class, cascade = [Cascade.PERSIST])
    @JoinTable(name = "enrolments", joinColumn = "course_id", inverseJoinColumn = "student_id")
    val students: List<Student>? = null,
)
@Entity("students") data class Student(
    @Id @Generated val id: String? = null, val name: String,
    @ManyToMany(Course::class)                                   // the same table, seen from the other side
    @JoinTable(name = "enrolments", joinColumn = "student_id", inverseJoinColumn = "course_id")
    val courses: List<Course>? = null,
)
@Entity("authors") data class Author(@Id @Generated val id: String? = null, val name: String,
    @OneToMany(Book::class) @JoinTable(name = "author_books") val books: List<Book>? = null)   // each book has one author
@Entity("books") data class Book(@Id @Generated val id: String? = null, val title: String,
    @ManyToOne(Publisher::class) @JoinTable(name = "book_publisher") val publisher: Publisher? = null)  // each book has one publisher

The table has its own key, the two id columns, and a unique constraint over the pair; one-to-many also makes the child column unique, and many-to-one the owner column. To see the same links from the other entity, declare a relation there with the same table name and the two columns swapped. name defaults to <table>_<property>, the columns to <table>_id and <target table>_id.

Write links explicitly, or by saving:

courses.link(math.id!!, "students", ann.id!!, bob.id!!)       // adds links, ignores ones that exist; a to-one relation replaces its link
courses.unlink(math.id!!, "students", bob.id!!)               // removes these; with no ids, all the links of this course
courses.save(course.copy(students = listOf(ann, cy)))         // cascade PERSIST: saves the students and makes the links exactly this set

null means not loaded

Saving makes the stored links match the list only when the property is not null. That is why a relation that cascades into a junction table (or removes orphans) must be declared List<X>? = null: null leaves the stored links alone, an empty list removes them all. The build fails if you declare it non-nullable.

Deleting an entity removes the link rows of its own relations. Deleting the other side leaves links that point at nothing; reads ignore them.

Loading

val team = teams.findWith(id, "players")                      // one extra query
val all = teams.fetch(list, "players.skills")                 // nested paths: one batched query per level
val joined = teams.findAllJoined("players")                   // one SQL LEFT JOIN (SQL: through join entities and junction tables too)

Batched loading issues one query per level however many parents there are (WHERE fk IN (...)). findAllJoined falls back to batching on MongoDB and across databases.

Cascades and orphans

@OneToMany(Box::class, "shelfId", cascade = [Cascade.PERSIST, Cascade.REMOVE], orphanRemoval = true)
val boxes: List<Box>? = null
  • PERSIST on a one-to-many: saving the parent saves the children with their foreign key set, in one transaction.
  • PERSIST on a many-to-one: saves the parent first and sets the foreign key.
  • PERSIST on a junction relation: saves the children and syncs the links.
  • REMOVE: deleting the parent deletes the children, recursively (junction links always go).
  • orphanRemoval = true (needs PERSIST): saving the parent deletes stored children that are no longer in the loaded list.

They run in one transaction when the entities share the parent's database. Java classes (not records) support the same.

Lazy properties

@Entity("authors") data class Author(
    @Id @Generated val id: String? = null, val name: String,
    @OneToMany(Novel::class, "authorId") val novels: Lazy<List<Novel>> = lazyOf(emptyList()),
)
author.novels.value        // runs the query on first access, once

A plain kotlin.Lazy, no proxy. fetch loads it eagerly. In Java declare the field as kotlin.Lazy<List<Novel>> with a getter and setter.

Filtering across a relation

interface TeamFinders : CrudRepository<Team, String> {
    fun findByPlayersName(name: String): List<Team>            // one hop: SQL EXISTS
}
interface LineFinders : CrudRepository<Line, String> {
    fun findByOrderCustomerName(name: String): List<Line>      // two hops: looked up step by step
}

On SQL one hop becomes an EXISTS semi-join (a parent appears once however many rows match, through junction tables too). Everything else (more hops, another database, MongoDB) is resolved by asking the related entity's own datastore for the matching ids first, then filtering on those: one extra query per hop.

Java records

Relations are not supported on Java records, because a record cannot be copied with a loaded relation. Use a Java class with setters, or a Kotlin data class.