问题描述
我只是尝试在h2中插入一个json值.然后我想用休眠转换器将这个json值作为对象返回.但是错误如下所示:
I just try to insert a json value in h2. Then I want to get back this json value as object with hibernate converter. But the error looks like below:
我的插入查询是:
INSERT INTO log(
id, activities, date)
VALUES (1, '[{"actionType": "EMAIL"}]', '2019-12-10 00:00:00');
当我尝试使用休眠转换器返回此字段时,该字段带有引号:
When I try to get back this field with hibernate converter, field comes with quotation mark:
"[{"actionType": "EMAIL"}]"
但是应该是:
[{"actionType": "EMAIL"}]
org.springframework.dao.InvalidDataAccessApiUsageException:无法将给定的字符串值"[{"actionType":" EMAIL}]"转换为Json对象;嵌套异常为java.lang.IllegalArgumentException:无法将给定的字符串值"[{"actionType":" EMAIL}]"转换为Json对象
org.springframework.dao.InvalidDataAccessApiUsageException: The given string value: "[{"actionType": "EMAIL"}]" cannot be transformed to Json object; nested exception is java.lang.IllegalArgumentException: The given string value: "[{"actionType": "EMAIL"}]" cannot be transformed to Json object
实体:
@Entity
@Table(name = "log")
public class RuleLog
{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Convert(converter = LogActionConverter.class)
private List<LogActivity> activities;
@Column(name = "date")
private LocalDateTime date;
}
转换器:
public class LogActionConverter implements AttributeConverter<List<LogActivity>, String>
{
private static final Gson gson = new Gson();
@Override
public String convertToDatabaseColumn(List<LogActivity> attribute)
{
try
{
if (attribute == null)
{
return null;
}
else
{
return gson.toJson(attribute);
}
}
catch (Exception ex)
{
return null;
}
}
@Override
public List<LogActivity> convertToEntityAttribute(String dbData)
{
try
{
if (dbData == null)
{
return null;
}
else
{
return gson.fromJson(dbData, List.class);
}
}
catch (Exception ex)
{
return null;
}
}
}
推荐答案
正如已经在 GitHub ,从字符串到 JSON 的转换JSON字符串对象.JSON文本应具有标准的 FORMAT JSON
子句,或被指定为非标准的 H2中的JSON文字.
As it was already answered on GitHub, the cast from a character string to a JSON creates a JSON String object. JSON text should either have a standard FORMAT JSON
clause or be specified as a non-standard JSON literal in H2.
-- SQL:2016 compliant
'[{"actionType": "EMAIL"}]' FORMAT JSON
-- or H2-specific
JSON '[{"actionType": "EMAIL"}]'
这篇关于H2数据库Json字段休眠转换器异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!