サンプルコード、githubにあげてます https://github.com/maeharin/kotlin-dvd-rental ● Kotlin x Spring Boot x Doma2で作ったAPIサーバーのサンプル ● DBにPostgreSQL、検索にElasticsearch(Dockerで起動) ● Postgresql tutorialのDVD Rentalサンプルデータベースを利用
@Service class FilmApplicationService( private val filmRepository: FilmDomaRepository ) { @Transactional fun create(command: FilmCommand): Int { @Repository class FilmDomaRepository( private val filmDao: FilmDao ) { DI
data class FilmResource( var name: String = "", var isAdmin: Boolean = false, var companyId: Int = 0 ) APIへのリクエスト(Json)をKotlinへマッピング Jacksonは デフォルト値ありの コンストラクタを要 求 デフォルト値は使い たくないのに。。
val source = FilmSource(film) val json = objectMapper.writeValueAsString(source) val indexRequest = IndexRequest(INDEX, TYPE, id) .source(json, XContentType.JSON) ElasticSearchとJsonやり取りする時も嬉しい data class => json
searchResponse.hits.map { hit -> val json = hit.sourceAsString val filmSource: FilmSource = objectMapper.readValue(json) } ElasticSearchとJsonやり取りする時も嬉しい json => data class
Kotlinの部分: Model, ValueObject class Film( val id: Int? = null, val title: String, val description: String?, val language: Language, val actors: List, val categories: List ) { ...
Kotlinの部分: Controller @RestController @RequestMapping("/api/v1/films") class FilmRestController( private val filmRepository: FilmDomaRepository ) { @GetMapping fun index(): List = filmRepository.findAll().map(::FilmResource)