Skip to content

Instantly share code, notes, and snippets.

@msrd0
Last active Dec 11, 2020
Embed
What would you like to do?
Read Exposed DAO Object from JSON using Jackson - https://stackoverflow.com/q/48158291/3755692
buildscript {
ext.exposedVersion = '0.9.0'
ext.h2Version = '1.4.196'
ext.jacksonVersion = '2.9.0'
ext.kotlinVersion = '1.2.10'
ext.logbackVersion = '1.2.3'
repositories {
jcenter()
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion"
}
}
apply plugin: 'kotlin'
apply plugin: 'application'
mainClassName = "Main"
repositories {
jcenter()
maven { url "https://dl.bintray.com/kotlin/exposed" }
}
dependencies {
compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlinVersion"
compile "org.jetbrains.kotlin:kotlin-reflect:$kotlinVersion"
compile "org.jetbrains.exposed:exposed:$exposedVersion"
compile "com.h2database:h2:$h2Version"
compile "com.fasterxml.jackson.module:jackson-module-kotlin:$jacksonVersion"
compile "ch.qos.logback:logback-classic:$logbackVersion"
}
sourceSets {
main.kotlin.srcDirs = ['src/']
}
@file:JvmName("Main")
import com.fasterxml.jackson.databind.introspect.*
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import org.jetbrains.exposed.sql.*
import org.jetbrains.exposed.sql.transactions.transaction
import org.jetbrains.exposed.sql.SchemaUtils.create
import org.jetbrains.exposed.dao.*
const val JSON = """{"name":"JSON Test"}"""
val mapper by lazy {
val mapper = jacksonObjectMapper()
mapper.setAnnotationIntrospector(object : JacksonAnnotationIntrospector() {
override fun hasIgnoreMarker(m : AnnotatedMember)
= (m.getDeclaringClass() == IntEntity::class.java)
|| (m.getDeclaringClass() == Entity::class.java)
|| super.hasIgnoreMarker(m)
})
mapper
}
fun main(args : Array<String>)
{
Database.connect("jdbc:h2:mem:test", driver = "org.h2.Driver")
transaction {
logger.addLogger(Slf4jSqlLogger)
create(UserTable)
User.new {
name = "Test"
}
User.new {
mapper.readerForUpdating(this).readValue(JSON)
}
}
}
import com.fasterxml.jackson.annotation.*
import org.jetbrains.exposed.sql.*
import org.jetbrains.exposed.dao.*
object UserTable : IntIdTable() {
val name = varchar("name", 256)
}
class User(id: EntityID<Int>): IntEntity(id) {
companion object : IntEntityClass<User>(UserTable)
@get:JsonProperty
var name by UserTable.name
}
@geofflangenderfer
Copy link

geofflangenderfer commented Dec 11, 2020

so the output is 2 database rows?

  • name = "Test"
  • name = "JSON Test"

@msrd0
Copy link
Author

msrd0 commented Dec 11, 2020

@geofflangenderfer Yes, that is the expected output.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment