我没有找到使用JPA(EclipseLink)从PostgreSQL映射JSON和JSONB数据类型的方法.有人在JPA中使用这种数据类型吗?能给我一些工作示例吗?

推荐答案

所有的答案都帮助我找到了最终的解决方案,为JPA而不是EclipseLink或Hibernate做好了准备.

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import javax.json.Json;
import javax.json.JsonObject;
import javax.persistence.Converter;
import org.postgresql.util.PGobject;

@Converter(autoApply = true)
public class JsonConverter implements javax.persistence.AttributeConverter<JsonObject, Object> {

  private static final long serialVersionUID = 1L;
  private static ObjectMapper mapper = new ObjectMapper();

  @Override
  public Object convertToDatabaseColumn(JsonObject objectValue) {
    try {
      PGobject out = new PGobject();
      out.setType("json");
      out.setValue(objectValue.toString());
      return out;
    } catch (Exception e) {
      throw new IllegalArgumentException("Unable to serialize to json field ", e);
    }
  }

  @Override
  public JsonObject convertToEntityAttribute(Object dataValue) {
    try {
      if (dataValue instanceof PGobject && ((PGobject) dataValue).getType().equals("json")) {
        return mapper.reader(new TypeReference<JsonObject>() {
        }).readValue(((PGobject) dataValue).getValue());
      }
      return Json.createObjectBuilder().build();
    } catch (IOException e) {
      throw new IllegalArgumentException("Unable to deserialize to json field ", e);
    }
  }
}

Postgresql相关问答推荐

Postgres:如何优化在多个表上搜索列的相似性查询?(Pg_Trgm)

ANTLR4 PostgreSQL语法被 destruct 了吗?

PostgreSQL存储过程中不存在游标

如何准确确定边界附近的点和地理的 ST_Intersects(ST_Intersects geography vs. Geometry diffrepancy)

在特定距离内创建点的唯一索引

如何在postgresql中按时间查询

PostgreSQL 如何比 SQLite 更快地执行写入?

Mac psql/readline - 未加载库

psql:致命:connection requires a valid client certificate

如何使用字符串作为 PostgreSQL 咨询锁的键?

如何在带有 PostgreSQL 数据库的 Web 应用程序中拥有完整的离线功能?

防止 CHARACTER VARYING 字段中出现空字符串

如何删除 Postgres 上的所有数据库?

null 计算结果为 false 的情况

PostgreSQL 条件 where 子句

PostgreSQL - 必须出现在 GROUP BY 子句中或在聚合函数中使用

处理用户发送的string contains null byte

Postgresql滚动删除旧行?

Ruby 中 DateTime 的毫秒分辨率

PostgreSQL - GROUP BY 子句或用于聚合函数