postgresql - 如何使用 spring-data-jdbc 读/写 postgres jsonb 类型?

标签 postgresql spring-boot jdbc spring-data spring-data-jdbc

我正在尝试将以下内容与 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 的帮助下我实现了以下解决方案:

  • 引入一个自己的类(POJO/kotlin 数据类),它包含 json 文档的结构(比如 MyContent)
  • 实现将 POJO 转换为字符串的写入和读取转换器(比如在 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/

    相关文章:

    php - 查询 postgresql 数组列

    function - PostgreSQL 中的更新函数

    java - 配置 Spring Boot Logback

    java - Controller 的 Spring Boot 测试 @WebMvcTest 似乎在上下文中加载其他 Controller

    mysql - JDBC 连接错误仍然存​​在

    Oracle Cast 和 MULTISET 在 POSTGRES 中可用

    Spring data jpa Query动态传递where子句

    spring-boot - 在类路径中具有 "spring-boot-starter-test"依赖项时无法启动 tomcat 服务器

    Java, JDBC : Does closing a PreparedStatement also free up its memory footprint in the database connection?

    mysql - Hibernate/c3p0/MySQL 下的网络延迟