Last active
December 12, 2021 12:56
-
-
Save bubbajoe/2106843ff71453fbed245396151d9626 to your computer and use it in GitHub Desktop.
Exposed Json Extension (works for MySQL)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.jetbrains.exposed.sql.Column | |
import org.jetbrains.exposed.sql.ColumnType | |
import org.jetbrains.exposed.sql.Table | |
fun <T : Any> Table.json(name: String, klass: Class<T>): Column<T> = | |
registerColumn(name, JsonTyped(klass)) | |
class JsonTyped<T : Any>(private val klass: Class<T>) : ColumnType() { | |
private val mapper = defaultObjectMapper // Please change this to whatever | |
override fun sqlType(): String = "json" | |
override fun valueFromDB(value: Any): Any { | |
try { | |
return mapper.readValue(value.toString(), klass) | |
} catch (e: Exception) { | |
// Logger here | |
throw RuntimeException("Can't parse JSON: '$value' to '$klass'") | |
} | |
} | |
override fun notNullValueToDB(value: Any): Any = mapper.writeValueAsString(value) | |
override fun nonNullValueToString(value: Any): String = "'${mapper.writeValueAsString(value)}'" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment