之前写过一篇文章《PostgreSQL如何使用json》
当时只介绍了在数据库层面使用json类型,本文总结在Java开发中使用数据库json类型的三种方式。
Hibernate注解映射
根据项目中Hibernate的版本参考hibernate-types提供的json类型
PostgreSQL
You should use this JsonBinaryType to map both jsonb and json column types.
Hibernate 5.5
<dependency>
<groupId>com.vladmihalcea</groupId>
<artifactId>hibernate-types-55</artifactId>
<version>2.14.0</version>
</dependency>
Hibernate 5.4, 5.3 and 5.2
<dependency>
<groupId>com.vladmihalcea</groupId>
<artifactId>hibernate-types-52</artifactId>
<version>2.14.0</version>
</dependency>
Hibernate 5.1 and 5.0
<dependency>
<groupId>com.vladmihalcea</groupId>
<artifactId>hibernate-types-5</artifactId>
<version>2.14.0</version>
</dependency>
Hibernate 4.3
<dependency>
<groupId>com.vladmihalcea</groupId>
<artifactId>hibernate-types-43</artifactId>
<version>2.14.0</version>
</dependency>
更详细设置参考:https://github.com/vladmihalcea/hibernate-types
Native Query
当某些功能不是通过映射框架进行处理,而是使用native query时可以通过cast函数进行类型转换。
INSERT INTO table(?,?)values(:?,:cast(:jsonString as json))
JDBC参数
最后是在jdbc里面可以通过一个连接参数stringtype来设置。
jdbc:postgresql://192.168.137.11:1304/postgres?stringtype=unspecified
测试截图如下:
表结构
应用程序中我们直接当成String来处理即可,数据存储到DB时,数据库会自动尝试做合适的类型转换。我们正常按照setString和getString来调用即可。
如果不加上面的stringtype连接参数,会出现下面的错误。
org.postgresql.util.PSQLException: ERROR: column "info" is of type json but expression is of type character varying
建议:You will need to rewrite or cast the expression.
位置:34
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2565)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2297)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:322)
at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:481)
at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:401)
at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:164)
at org.postgresql.jdbc.PgPreparedStatement.execute(PgPreparedStatement.java:153)
at TestJson.main(TestJson.java:29)
保持联系
从2019年12月开始写第一篇文章,分享的初心一直在坚持,本人现在组建了一个PG乐知乐享交流群,欢迎关注我文章的小伙伴进群吹牛唠嗑,交流技术,互赞文章。
如果群二维码失效可以加我微信。
最后修改时间:2022-10-23 10:31:24
「喜欢这篇文章,您的关注和赞赏是给作者最好的鼓励」
关注作者
【版权声明】本文为墨天轮用户原创内容,转载时必须标注文章的来源(墨天轮),文章链接,文章作者等基本信息,否则作者和墨天轮有权追究责任。如果您发现墨天轮中有涉嫌抄袭或者侵权的内容,欢迎发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。