Guest User

Untitled

a guest
Jan 17th, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.26 KB | None | 0 0
  1. import com.fasterxml.jackson.databind.ObjectMapper
  2. import org.jetbrains.exposed.sql.Column
  3. import org.jetbrains.exposed.sql.ColumnType
  4. import org.jetbrains.exposed.sql.Table
  5. import org.postgresql.util.PGobject
  6. import java.sql.PreparedStatement
  7.  
  8. /**
  9. * Created by quangio.
  10. */
  11.  
  12. fun <T : Any> Table.jsonb(name: String, klass: Class<T>, jsonMapper: ObjectMapper): Column<T>
  13. = registerColumn(name, Json(klass, jsonMapper))
  14.  
  15.  
  16. private class Json<out T : Any>(private val klass: Class<T>, private val jsonMapper: ObjectMapper) : ColumnType() {
  17. override fun sqlType() = "jsonb"
  18.  
  19. override fun setParameter(stmt: PreparedStatement, index: Int, value: Any?) {
  20. val obj = PGobject()
  21. obj.type = "jsonb"
  22. obj.value = value as String
  23. stmt.setObject(index, obj)
  24. }
  25.  
  26. override fun valueFromDB(value: Any): Any {
  27. value as PGobject
  28. return try {
  29. jsonMapper.readValue(value.value, klass)
  30. } catch (e: Exception) {
  31. e.printStackTrace()
  32. throw RuntimeException("Can't parse JSON: $value")
  33. }
  34. }
  35.  
  36.  
  37. override fun notNullValueToDB(value: Any): Any = jsonMapper.writeValueAsString(value)
  38. override fun nonNullValueToString(value: Any): String = "'${jsonMapper.writeValueAsString(value)}'"
  39. }
Add Comment
Please, Sign In to add comment