我正在尝试将以下内容与 spring-data-jdbc 和 postgres 驱动程序(kotlin)一起使用,
data class MyEntity(
val id: UUID,
val content: String
)
使用字符串失败并出现以下错误,org.postgresql.util.PSQLException: ERROR: column "content" is of type jsonb but expression is of type character varying
Hint: You will need to rewrite or cast the expression.
Position: 31
我不确定如何将转换器用于 String -> jsonb
最佳答案
在 this 的帮助下我实现了以下解决方案:
MyContent
)jackson
的帮助下)org.postgresql.util.PGobject
的帮助下指定 postgres 列类型详情(仅伪代码):
import org.springframework.core.convert.converter.Converter
import org.springframework.data.convert.ReadingConverter
import org.springframework.data.convert.WritingConverter
import com.fasterxml.jackson.databind.ObjectMapper
import org.postgresql.util.PGobject
@Table("my_entity")
data class MyEntity(
@Id val id: UUID,
val content: MyContent
) {
@WritingConverter
class EntityWritingConverter(
private val objectMapper: ObjectMapper
) : Converter<MyContent, PGobject> {
override fun convert(source: MyContent): PGobject? {
val jsonObject = PGobject()
jsonObject.type = "json"
jsonObject.value = objectMapper.writeValueAsString(source)
return jsonObject
}
}
@ReadingConverter
class EntityReadingConverter(
private val objectMapper: ObjectMapper
) : Converter<PGobject, MyContent> {
override fun convert(pgObject: PGobject): MyContent {
val source = pgObject.value
return objectMapper.readValue<MyContent>(source)
}
}
}
不要忘记将两个转换器添加到 spring-data-jdbc
s 配置(见 JdbcCustomConversions
)。这适用于这个相应的 postgres 表:
create table if not exists my_entity
(
id uuid not null primary key,
content jsonb
);
关于postgresql - 如何使用 spring-data-jdbc 读/写 postgres jsonb 类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64521056/