【问题标题】:Map string properties to JSONB将字符串属性映射到 JSONB
【发布时间】:2020-12-27 04:50:02
【问题描述】:

我一直在尝试使用 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();
}

【问题讨论】:

    标签: java postgresql hibernate jpa


    【解决方案1】:

    我终于找到了解决问题的方法。答案是 - 只需通过 getter 使用您的 @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;
    }
      
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-11-24
        • 1970-01-01
        • 2012-10-20
        • 2018-01-22
        • 2013-06-06
        • 1970-01-01
        • 2012-01-23
        • 2019-05-11
        相关资源
        最近更新 更多