我试图保存一个具有JsonNode属性的实体,必须转换为jsonb才能存储在postgres数据库中。
这是数据库表:
CREATE TABLE IF NOT EXISTS configuration_data (
id SERIAL NOT NULL PRIMARY KEY,
namespace_name TEXT NOT NULL,
dimension_id TEXT NOT NULL,
dimension_value TEXT,
path TEXT,
data JSONB,
version BIGINT DEFAULT 0
);
这是实体:
@MappedEntity(value = "configuration_data")
data class ConfigurationDataEntity(
@field:Id @GeneratedValue
val id: Long,
@MappedProperty("namespace_name")
val namespaceName: String,
@MappedProperty("dimension_id")
val dimensionId: String,
@MappedProperty("dimension_value")
val dimensionValue: String,
@MappedProperty("path")
val path: String,
@MappedProperty("data")
val data: JsonNode,
@MappedProperty("version")
val version: Long,
)
我正在尝试将这样的实体保存到存储库中:
val entity = ConfigurationDataEntity(1L, coordinates.namespace, "acc", "abc", "path", data, 1L)
repository.save(entity)
我得到的错误如下:
Caused by: io.micronaut.data.exceptions.DataAccessException: Error executing PERSIST: Unable to set PreparedStatement value: Can't infer the SQL type to use for an instance of com.fasterxml.jackson.databind.node.ObjectNode. Use setObject() with an explicit Types value to specify the type to use.
我想这是因为postgres不能在jsonb对象中存储jsonNode,但我不知道如何将jsonNode转换为jsonb。
提前谢谢你:)
将此注释添加到字段:
@field:TypeDef(type = DataType.JSON)
所以实体保持如下:
@MappedEntity(value = "configuration_data")
data class ConfigurationDataEntity(
@field:Id @GeneratedValue
val id: Long,
@MappedProperty("namespace_name")
val namespaceName: String,
@MappedProperty("dimension_id")
val dimensionId: String,
@MappedProperty("dimension_value")
val dimensionValue: String,
@MappedProperty("path")
val path: String,
@MappedProperty("data")
**@field:TypeDef(type = DataType.JSON)**
val data: JsonNode,
@MappedProperty("version")
val version: Long,
)