【发布时间】:2020-11-27 17:13:39
【问题描述】:
我有如下表定义
create table samples (
channel text,
eventType text,
data json NOT NULL
);
我也尝试将data 列定义为clob,text,java_object,varchar,other。
我正在使用以下 API 在 h2 中插入数据:
def insert(sample: Sample): Unit = DB localTx { implicit session =>
val propertiesJson = new PGobject()
propertiesJson.setType("json")
propertiesJson.setValue(sample.properties.toJson.toString)
sql"""
insert into samples
(channel,eventType,data) values (${sample.channel}, ${sample.eventType},$propertiesJson )
""".update().apply()
}
还有这个来检索数据
def find(channel: String): List[Sample] = DB readOnly { implicit session =>
sql"""
select * from samples where channel = $channel
""".map(rs => {
Sample(
channel = rs.string("channel"),
properties = rs.string("data").parseJson.convertTo[Map[String, String]],
eventType = rs.string("eventType")
)
}
).list().apply()
}
我正在使用 spray 和 scalikejdbc 驱动程序进行隐式转换。
根据data 列的数据类型,我会遇到不同的错误。
-
对于
CLOB,VARCHAR,TEXT和JAVA_OBJECT:我可以在 h2 中插入数据,但在尝试检索时我得到了spray.json.JsonParser$ParsingException: Unexpected character 'a' at input index 0 (line 1, position 1), expected JSON Value: aced00057372001c6f72672e706f737467726573716c2e7574696c2e50476f626a656374f903de2682bdcb3b0200024c0004747970657400124c6a6176612f6c616e672f537472696e673b4c000576616c756571007e000178707400046a736f6e74001f7b2270726f7041223a2276616c41222c2270726f7042223a2276616c42227d -
对于
JSON。我什至无法将数据插入 h2。我来了Caused by: org.h2.jdbc.JdbcSQLDataException: Data conversion error converting "OTHER to JSON" [22018-200] at org.h2.message.DbException.getJdbcSQLException(DbException.java:457) at org.h2.message.DbException.getJdbcSQLException(DbException.java:429) ... 114 more
使用JSON的时候我也试过这个format json指令建议here
另见 json 文字语法。映射到字节[]。设置 JSON 值 在 PreparedStatement 中使用 java.lang.String 使用 FORMAT JSON 数据 格式(插入测试(ID,数据)值(?,?格式 JSON))。没有 将数据格式 VARCHAR 值转换为 JSON 字符串值。
但错误还是一样。
所以有什么想法吗?如何从 h2 数据库中成功插入和检索 JSON 数据?我的方法有什么问题吗?
【问题讨论】:
标签: scala h2 scalikejdbc