在Postgres中创建一个表。
CREATE TABLE demoJson(
id SERIAL NOT NULL PRIMARY KEY,
jsonData JSONB NOT NULL
);
我创建了一个名为DemoJsonEnitity的Hibernate实体类,并定义@TypeDefs。
@Entity
@Table(name = "demoJson")
@TypeDefs({
@TypeDef(name = "json", typeClass = JsonStringType.class)
,
@TypeDef(name = "jsonb", typeClass = JsonBinaryType.class)
})
public class DemoJsonEnitity implements Serializable {
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "id")
private int dataId;
@Type(type = "jsonb")
@Column(name = "jsonData", columnDefinition = "jsonb")
private String jsonData;
public int getDataId() {
return dataId;
}
public void setDataId(int dataId) {
this.dataId = dataId;
}
public String getJsonData() {
return jsonData;
}
public void setJsonData(String jsonData) {
this.jsonData = jsonData;
}
}
就是这样。非常简单,我使用了这个依赖项
<dependency>
<groupId>com.vladmihalcea</groupId>
<artifactId>hibernate-types-52</artifactId>
<version>2.9.11</version>
</dependency>
为了检查,我尝试将数据保存为
public static void main(String arg[]) {
try {
DemoJsonEnitity obj = new DemoJsonEnitity();
JSONObject jsonObj = new JSONObject();
Map m1 = new LinkedHashMap(2);
m1.put("oldValue", "Active");
m1.put("newValue", "InActive");
jsonObj.put("status", m1);
Map m2 = new LinkedHashMap(2);
m2.put("oldValue", "Test 6");
m2.put("newValue", "Test 6 updated");
jsonObj.put("taskDetails", m2);
obj.setJsonData(jsonObj.toString());
Session session = null;
Transaction tx = null;
try {
session = sf.openSession();
tx = session.beginTransaction();
session.save(obj);
tx.commit();
} catch (Exception e) {
if (tx != null) {
tx.rollback();
}
throw new RuntimeException(e);
} finally {
session.close();
}
} catch (Exception e) {
System.out.println("error: " + e.getMessage());
}
}
输出
![enter image description here](https://istack.dev59.com/Uzkv6.webp)