将PostgreSQL JSON列映射到Hibernate实体属性 [英] Mapping PostgreSQL JSON column to a Hibernate entity property

查看:208
本文介绍了将PostgreSQL JSON列映射到Hibernate实体属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在PostgreSQL数据库(9.2)中有一个表,其中的列为JSON类型.我很难将此列映射到"JPA2实体"字段类型.

我尝试使用String,但是当我保存实体时,出现一个异常,它无法将字符转换为JSON.

处理JSON列时使用什么正确的值类型?

@Entity
public class MyEntity {

    private String jsonPayload; // this maps to a json column

    public MyEntity() {
    }
}

一个简单的解决方法是定义一个文本列.

解决方案

请参阅PgJDBC错误#265 ./p>

PostgreSQL对数据类型转换过分严格,令人讨厌.即使是像xmljson这样的文本值,它也不会隐式转换text.

解决此问题的严格正确方法是编写使用JDBC setObject方法的自定义Hibernate映射类型.这可能有点麻烦,所以您可能只想通过创建较弱的强制转换来降低PostgreSQL的严格性.

@markdsievers在评论和中指出此博客帖子,此答案中的原始解决方案会绕过JSON验证.因此,这并不是您真正想要的.写起来更安全:

CREATE OR REPLACE FUNCTION json_intext(text) RETURNS json AS $$
SELECT json_in($1::cstring); 
$$ LANGUAGE SQL IMMUTABLE;

CREATE CAST (text AS json) WITH FUNCTION json_intext(text) AS IMPLICIT;

AS IMPLICIT告诉PostgreSQL它可以转换而无需明确地告诉它,从而允许这样的事情起作用:

regress=# CREATE TABLE jsontext(x json);
CREATE TABLE
regress=# PREPARE test(text) AS INSERT INTO jsontext(x) VALUES ($1);
PREPARE
regress=# EXECUTE test('{}')
INSERT 0 1

感谢@markdsievers指出了这个问题.

I have a table with a column of type JSON in my PostgreSQL DB (9.2). I have a hard time to map this column to a JPA2 Entity field type.

I tried to use String but when I save the entity I get an exception that it can't convert character varying to JSON.

What is the correct value type to use when dealing with a JSON column?

@Entity
public class MyEntity {

    private String jsonPayload; // this maps to a json column

    public MyEntity() {
    }
}

A simple workaround would be to define a text column.

解决方案

See PgJDBC bug #265.

PostgreSQL is excessively, annoyingly strict about data type conversions. It won't implicitly cast text even to text-like values such as xml and json.

The strictly correct way to solve this problem is to write a custom Hibernate mapping type that uses the JDBC setObject method. This can be a fair bit of hassle, so you might just want to make PostgreSQL less strict by creating a weaker cast.

As noted by @markdsievers in the comments and this blog post, the original solution in this answer bypasses JSON validation. So it's not really what you want. It's safer to write:

CREATE OR REPLACE FUNCTION json_intext(text) RETURNS json AS $$
SELECT json_in($1::cstring); 
$$ LANGUAGE SQL IMMUTABLE;

CREATE CAST (text AS json) WITH FUNCTION json_intext(text) AS IMPLICIT;

AS IMPLICIT tells PostgreSQL it can convert without being explicitly told to, allowing things like this to work:

regress=# CREATE TABLE jsontext(x json);
CREATE TABLE
regress=# PREPARE test(text) AS INSERT INTO jsontext(x) VALUES ($1);
PREPARE
regress=# EXECUTE test('{}')
INSERT 0 1

Thanks to @markdsievers for pointing out the issue.

这篇关于将PostgreSQL JSON列映射到Hibernate实体属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆