我正在使用 PostgreSQL 和 Hibernate 6,并且我有一个 JSONB 类型列 -
values
。
问题是,如何为该字段定义一个具有泛型类型的实体? 另外,有没有办法在反序列化过程中根据第二个 ENUM 字段映射正确的类 -
type
?
类似:
@Getter
@Setter
@Entity
@Table(name = "setting")
public class SettingEntity<T> {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Enumerated(EnumType.STRING)
private SettingType type;
@JdbcTypeCode(SqlTypes.JSON)
private T values;
}
我找不到如何做到这一点的明确解释。感谢您的帮助。
你好吗?
您是否尝试过使用 Jackson 库来协助对象序列化?
您的代码将如下所示:
@Getter
@Setter
@Entity
@Table(name = "setting")
public class SettingEntity<T> {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Enumerated(EnumType.STRING)
private SettingType type;
@Column(columnDefinition = "jsonb")
@Convert(converter = JsonConverter.class)
private T values;
}
此外,您需要创建一个转换器来处理泛型类型的 JSON 转换:
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.io.IOException;
@Converter
public class JsonConverter<T> implements AttributeConverter<T, String> {
private final ObjectMapper objectMapper = new ObjectMapper();
@Override
public String convertToDatabaseColumn(T attribute) {
try {
return objectMapper.writeValueAsString(attribute);
} catch (IOException e) {
throw new IllegalArgumentException("Error converting JSON to string", e);
}
}
@Override
public T convertToEntityAttribute(String dbData) {
try {
return objectMapper.readValue(dbData, new TypeReference<T>() {});
} catch (IOException e) {
throw new IllegalArgumentException("Error converting string to JSON", e);
}
}
}
在上面的示例中,JsonConverter 类使用 Jackson 实现 AttributeConverter 来序列化和反序列化 JSON 对象。
不要忘记添加 Maven 依赖项:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>VERSION</version>
</dependency>
或者如果您使用 Gradle:
dependencies {
implementation 'com.fasterxml.jackson.core:jackson-databind:VERSION'
}
记住将“VERSION”替换为与您的项目兼容的 Jackson 版本!