使用PostgreSQL JSONB类型和Hibernate Reactive



我正在将我的Quarkus项目从经典的Hibernate ORM迁移到Hibernate Reactive,我遇到了JSONB字段映射的问题。

这是实体:

@Entity
@TypeDef(name = JsonTypes.JSON_BIN, typeClass = JsonBinaryType::class)
class MyEntity {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "myEntityIdGenerator")
@SequenceGenerator(name = "myEntityIdGenerator", sequenceName = "my_entity_id_seq", allocationSize = 10)
var id: Long? = null
// Usage of a plain JsonNode instead of a mapped class is intentional, 
// as the app receives a request with raw JSON data and should store it without any processing
@Type(type = JsonTypes.JSON_BIN)
@NotNull
lateinit var jsonData: JsonNode
}

该项目具有处理JSON类型的io.quarkiverse.hibernatetypes:quarkus-hibernate-types:0.2.0依赖项。

这段代码可以很好地阻止Hibernate API,但当试图使用Hibernate Reactive持久化MyEntity时,我得到了以下异常:

io.vertx.core.impl.NoStackTraceThrowable: Parameter at position[1] with class = [com.fasterxml.jackson.databind.node.ObjectNode] and value = [{"field1":"some value"}] can not be coerced to the expected class = [java.lang.Object] for encoding.

这是一个错误还是在使用Hibernate Reactive时应该以不同的方式处理自定义类型?

Hibernate Types与Hibernate Reactive不兼容。

但是你有三个选项可以用Hibernate Reactive:映射Json

  1. 使用io.vertx.core.json.JsonObject
  2. 将其映射为字符串并使用转换器
  3. 创建用户类型

1.JsonObject

io.vertx.core.json.JsonObject示例:

@Entity
private static class EntityWithJson {
...
private JsonObject jsonObj;
...
}

您可以在存储库中看到一个工作示例:JsonTypeTest

2.使用转换器

使用转换器的示例:

class EntityWithJson {
@Column(columnDefinition = "json")
@Convert(converter = StringToJson.class)
private String json;
...
}
@Converter
public class StringToJson implements AttributeConverter<String, JsonObject> {
@Override
public JsonObject convertToDatabaseColumn(String string) {
if (string == null) {
return null;
}
return new JsonObject(string);
}
@Override
public String convertToEntityAttribute(JsonObject dbData) {
if (dbData == null) {
return null;
}
return dbData.encodePrettily();
}
}

您可以在存储库中看到一个工作示例:JsonTypeTest

3.用户类型

class EntityWithJson {

@Type(type="org.example.Json")
@Column(columnDefinition = "json")
private JsonObject jsonObj;
}
package org.example
public class Json implements UserType {
// ... Implementation left out for brevity
}

您可以在存储库中看到一个工作示例:UserJsonTypeTest

要存储postgres类型为JSONB的字段,我们可以使用注释:

@JdbcTypeCode(SqlTypes.JSON(

这将自动创建具有JsonB数据类型的表列。

最新更新