San*_*gam 6 postgresql jdbc spring-data spring-boot spring-data-jdbc
我尝试将以下内容与 spring-data-jdbc 和 postgres 驱动程序(kotlin)一起使用,
data class MyEntity(
val id: UUID,
val content: String
)
Run Code Online (Sandbox Code Playgroud)
使用字符串失败并出现以下错误,
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
Run Code Online (Sandbox Code Playgroud)
我不确定如何使用 String -> jsonb 转换器
在此帮助下,我实现了以下解决方案:
MyContent)jackson)org.postgresql.util.PGobject详细信息(仅伪代码):
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)
}
}
}
Run Code Online (Sandbox Code Playgroud)
不要忘记将两个转换器添加到spring-data-jdbcs 配置中(请参阅 参考资料JdbcCustomConversions)。
这适用于相应的 postgres 表:
create table if not exists my_entity
(
id uuid not null primary key,
content jsonb
);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10087 次 |
| 最近记录: |