将字符串属性映射到JSONB

时间:2020-09-08 18:57:32

标签: java postgresql hibernate jpa

我一直在尝试使用JPA将字符串属性映射到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,并且效果很好
  2. 但是我想对我的基础实体类使用抽象层并设置上面已经提到的注释,然后在异常之后说“你好!又是我'

我的层次结构非常简单,就在这里:

基本实体

@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;

我的桌子

create table ref.test_json_3
(
id serial primary key,
json_property jsonb 
)

UPD 我已经成功地用JPA本机查询插入了记录,但是我不得不将查询解包到休眠查询中。不确定这是管理将数据插入数据库的最便捷方法。我的问题是实际的,我仍然需要您的帮助)下面带有本地查询的示例。

带有结果的代码片段

@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();
}

1 个答案:

答案 0 :(得分:0)

最后,我找到了解决问题的方法。答案是-只需通过吸气剂使用@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;
}