Hibernate H2数据库Json字段休眠转换器异常
我只是尝试在h2中插入一个json值。然后我想用hibernate转换器将这个json值作为对象返回。但错误如下所示: 我的插入查询是:Hibernate H2数据库Json字段休眠转换器异常,hibernate,unit-testing,h2,Hibernate,Unit Testing,H2,我只是尝试在h2中插入一个json值。然后我想用hibernate转换器将这个json值作为对象返回。但错误如下所示: 我的插入查询是: INSERT INTO log( id, activities, date) VALUES (1, '[{"actionType": "EMAIL"}]', '2019-12-10 00:00:00'); 当我尝试使用hibernate converter取回此字段时,该字段带有引号: "[{"actionType": "EMAIL"}]" 但它应该是:
INSERT INTO log(
id, activities, date)
VALUES (1, '[{"actionType": "EMAIL"}]', '2019-12-10 00:00:00');
当我尝试使用hibernate converter取回此字段时,该字段带有引号:
"[{"actionType": "EMAIL"}]"
但它应该是:
[{"actionType": "EMAIL"}]
org.springframework.dao.InvalidDataAccessApiUsageException:给定字符串值“[{”actionType:“EMAIL”}]”无法转换为Json对象;嵌套异常是java.lang.IllegalArgumentException:给定的字符串值“[{”actionType:“EMAIL”}]”无法转换为Json对象
实体:
@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;
}
@实体
@表(name=“log”)
公共类规则日志
{
@身份证
@GeneratedValue(策略=GenerationType.IDENTITY)
私人长id;
@Convert(converter=LogActionConverter.class)
私人名单活动;
@列(name=“date”)
私有LocalDateTime日期;
}
转换器:
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;
}
}
}
公共类LogActionConverter实现AttributeConverter
{
私有静态最终Gson Gson=new Gson();
@凌驾
公共字符串convertToDatabaseColumn(列表属性)
{
尝试
{
if(属性==null)
{
返回null;
}
其他的
{
返回gson.toJson(属性);
}
}
捕获(例外情况除外)
{
返回null;
}
}
@凌驾
公共列表convertToEntityAttribute(字符串dbData)
{
尝试
{
if(dbData==null)
{
返回null;
}
其他的
{
返回gson.fromJson(dbData,List.class);
}
}
捕获(例外情况除外)
{
返回null;
}
}
}
正如上面已经回答的那样,从字符串到字符串的转换将创建一个JSON字符串对象。JSON文本应该有一个标准的格式JSON
子句,或者在H2中指定为非标准
——SQL:2016兼容
“[{”actionType:“EMAIL”}]'格式的JSON
--或H2特异性
JSON'[{“actionType”:“EMAIL”}]'