10. —
object Books : Table() {
val id: Column<Int> = integer("id")
.autoIncrement()
.primaryKey()
val title: Column<String> = varchar("title", 255)
val isbn: Column<String> = varchar("isbn", 13)
val publishedAt: Column<DateTime> = datetime("...")
}
object Books : IntIdTable() {
val title = varchar("title", 255)
val isbn = varchar("isbn", 13)
val publishedAt = datetime("...")
}
11. DAO
—
class Book(id: EntityID<Int>) : IntEntity(id) {
companion object : IntEntityClass<Book>(Books)
var title by Books.title
var isbn by Books.isbn
var publishedAt by Books.publishedAt
}
16. // create
Book.new {
title = ...
}
// read
Book.all()
Book.find { ... }
.sortedBy { it.id }
// update
val book = Book.findById(...)
if (book != null) {
book.title = ...
}
// delete
val book = Book.findById(1)
book?.delete()
CRUD (DAO)
—
17. object Books : IntIdTable() {
val title = varchar("title", 255)
val isbn = varchar("isbn", 13)
val publishedAt = datetime(“published_at")
val author = reference("author", Authors)
}
object Authors: IntIdTable() {
val name = varchar("name", 255)
}
(Table)
—
18. class Book(id: EntityID<Int>) : IntEntity(id) {
companion object : IntEntityClass<Book>(Books)
var title by Books.title
var isbn by Books.isbn
var publishedAt by Books.publishedAt
var author by Author referencedOn Books.author
}
class Author(id: EntityID<Int>): IntEntity(id) {
companion object: IntEntityClass<Author>(Authors)
var name by Authors.name
val books by Book referrersOn Books.author
}
(Entity)
—
19. Book.all().map {
println("(${it.title} by ${it.author.name}")
}
Author.all().map { author ->
author.books.forEach {
println("${author.name} wrote ${it.title}")
}
}
—
21. JSON API
—
// define respond class
data class BookRespond(
val title:String,
val author: String,
val isbn: String,
val publishedAt: String
)
// define api
get("/api/v1/books") {
val books = transaction {
Book.all().sortedByDescending { it.id }.map {
BookRespond(
title = it.title,
isbn = it.isbn,
publishedAt = ...,
author = it.author.name
)
}
}
call.respond(mapOf("books" to books))
}