Persist PostgreSQL Json datatype with Hibernate

前端之家收集整理的这篇文章主要介绍了Persist PostgreSQL Json datatype with Hibernate前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

在PG数据库中要额外创建以下Function和Cast(必须创建):

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

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

数据库中表的sql定义

drop table if exists tabx;
create table tabx
(
	id bigint PRIMARY KEY NOT NULL,device_id bigint references hdata_device_info(id),pcie_info json,sample_time timestamp
);

在entity中的类型定义(对应字段使用String类型)

@Entity
@Table(name="hdata_pcie_info")
@NamedQuery(name="HdataPcieInfo.findAll",query="SELECT h FROM HdataPcieInfo h")
public class Tabx implements Serializable
{
	private static final long serialVersionUID = 1L;
	
	@TableGenerator(name="tabx_id_generator",table="id_generator",pkColumnName="pk_name",pkColumnValue="pcie_info_id",valueColumnName="pk_value",allocationSize=1)
    
        @Id
        @GeneratedValue(strategy=GenerationType.TABLE,generator="tabx_id_generator")
	private Long id;

	@Column(name="pcie_info")
	private String pcieInfo;

	@Column(name="sample_time")
	private Timestamp sampleTime;

	//bi-directional many-to-one association to HdataDeviceInfo
	@ManyToOne
	@JoinColumn(name="device_id")
	private HdataDeviceInfo hdataDeviceInfo;
    
        //get or set method

保存json数据:

logger.debug(jsonArray.toString());
entity.setPcieInfo(jsonArray.toString());			
//String json = "{\"username\":\"john\",\"posts\":121,\"emailaddress\":\"john@nowhere.com\"}";
//entity.setPcieInfo(json)

猜你在找的Postgre SQL相关文章