首页 > 解决方案 > 休眠 json 映射与 psql 数据库

问题描述

使用 JPA,我尝试将 @Entity 类的对象映射到 postgres DB json 列。

@Enity
public class MyEntity{

@NotNull
@ToString.Exclude
@Convert(converter = JsonSerializationConverter.class)
private Object value;
}
public class JsonSerializationConverter implements AttributeConverter<Object, String> {

    private static final ObjectMapper mapper = new ObjectMapper();

    @SneakyThrows
    @Override
    public String convertToDatabaseColumn(final Object attribute) {
        return mapper.writeValueAsString(attribute);
    }

在本地运行时,它的工作原理就像一个魅力,但由于未知原因,它无法在 k8n pod 上的 azure cloud 中运行:

SchemaManagementException: Schema-validation: wrong column type encountered in column [value] in table [preference] found [json (Types#OTHER)], but expecting [varchar(255)

主要是其他stackoverflow问题参考这个:postgre bug并建议设置data-source-properties:stringtype = unspecified

不幸的是,这并不能解决 azure kn8 ubuntu pod 中的问题。我都试过了:

spring.datasource.url: jdbc:postgresql://xyz:5432/dbname?stringtype=unspecified
spring.datasource.hikari.data-source-properties.stringtype: unspecified

标签: javapostgresqlhibernate

解决方案


原因是它在本地工作的原因是 spring.jpa.hibernate.ddl-auto: none (并在 K8n 中验证)

但是对于所有 ENV,这解决了这个问题:

@Enity
public class MyEntity{

@NotNull
@ToString.Exclude
//this resolved the issue
@Column(name = "value", columnDefinition = "json")
@Convert(converter = JsonSerializationConverter.class)
private Object value;
}

只是不适用于 zonky 嵌入式 postgre


推荐阅读