java 将字符串属性Map到JSONB

suzh9iv8  于 2023-01-11  发布在  Java
关注(0)|答案(3)|浏览(132)

我一直在尝试使用JPA将字符串属性Map到Postgresql的JSONB。我确实多次阅读了perfect article by Vlad Mihalcea,也看到了类似内容的相关问题。但每次我尝试向表中插入内容时,仍然会遇到org.postgresql.util.PSQLException: ERROR: column "json_property" is of type jsonb but expression is of type character varying异常。
更糟糕的是-所有这些建议在类似的问题是有用的,直到我改变了我的实体类,使他继承超类。现在的情况是这样的:
1.如果在我的子类上使用@TypeDef@Type,它工作得很好
1.但是我想使用抽象层并设置注解,这是我在上面注意到的,到我的基本实体类,并在异常之后说“你好!又是我”
我的层次结构非常简单,如下所示:

基本实体

@TypeDef(name = "jsonb", typeClass = JsonBinaryType.class)
@MappedSuperclass
public abstract class AbstractServiceEntity implements Serializable {

private Integer id;

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
public Integer getId() {
    return id;
}

public void setId(Integer id) {
    this.id = id;
}

子实体

@Entity
@Table(schema = "ref", name = "test_json_3")
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
public class TestJson extends AbstractServiceEntity {

@Type(type = "jsonb")
@Column(columnDefinition = "jsonb")
private String jsonProperty;

我的table

create table ref.test_json_3
(
id serial primary key,
json_property jsonb 
)
  • UPD* 我已经成功地用JPA原生查询插入了记录,但是我不得不将我的查询解包到休眠查询中。不确定这是管理将数据插入到DB中的最方便的方法。我的问题是实际的,我仍然需要你的帮助)下面是原生查询的示例。
    带有结果的代码片段
@Repository
public class JpaTestRepository {

@PersistenceContext
private EntityManager entityManager;

@Transactional
public void insert(TestJson testJson) {
    entityManager.createNativeQuery("INSERT INTO test_json_3 (json_property) VALUES (?)")
            .unwrap(Query.class)
            .setParameter(1, testJson.getJsonProperty(), JsonBinaryType.INSTANCE)
            .executeUpdate();
}
kgsdhlau

kgsdhlau1#

最后我找到了解决我问题的方法。答案是-只需要通过getters使用你的@Column(columnDefinition = "jsonb")@Type(type = "jsonb",而不是类属性。

实体定义

@Entity
@Table(schema = "ref", name = "test_json_3")
@NoArgsConstructor
@AllArgsConstructor
@Setter
public class TestJson extends AbstractServiceEntity {

private String jsonProperty;

@Type(type = "jsonb")
@Column(columnDefinition = "jsonb")
public String getJsonProperty() {
    return jsonProperty;
}
kmpatx3s

kmpatx3s2#

您可以尝试在类TestJson下添加@TypeDefs:

@TypeDefs({
        @TypeDef(name = "jsonb", typeClass = JsonBinaryType.class)
})
public class TestJson extends AbstractServiceEntity {
3xiyfsfu

3xiyfsfu3#

将StringMap到Jsonb类型的替代解决方案。只需在字符串上添加以下注解。

@ColumnTransformer(write = "?::jsonb")
private String jsonProperty;

相关问题