我不明白如何使用jsonb和Spring Data JDBC将实体保存到数据库

问题描述 投票:0回答:1

我的 Spring Boot 应用程序中有一个实体:

@Data
@AllArgsConstructor
@Table(name = "my_files")
public class myFile {

@Id private Long id;

private String content;
}

这是与该实体对应的表:

create table if not exists my_files

(
id bigint not null primary key,
content jsonb
);

问题是当我尝试将实体放入数据库时,出现以下错误:

Caused by: org.postgresql.util.PSQLException: ERROR: column "file_data" is of type jsonb but expression is of type character varying
Hint: You will need to rewrite or cast the expression.

我知道我需要将字符串转换为jsonb。我找到了几个关于如何为 Hibernate 执行此操作的指南,但我在我的项目中使用 Spring Data JDBC,并且不知道如何解决这个问题。请帮我找到解决方案。

我试图找到解决方案,但它们都适用于 Hibernate。

java postgresql spring-boot jsonb spring-data-jdbc
1个回答
0
投票

从 String 到 JSON 类型的转换可以由 Hibernate(Spring Boot Data JPA 的一部分)在内部完成。只需将此注释添加到实体中的字段定义即可:

import org.hibernate.annotations.JdbcTypeCode;
import org.hibernate.type.SqlTypes;
// ...
    @JdbcTypeCode(SqlTypes.JSON)
    private String content;

© www.soinside.com 2019 - 2024. All rights reserved.