H2 Database Json Field Hibernate Converter Exception

随声附和 提交于 2021-02-10 20:11:55

问题


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:

My insert query is:

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"}]"

But it should be:

[{"actionType": "EMAIL"}]

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:

@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;
}

Converter:

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;
        }
    }
}

回答1:


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"}]'


来源:https://stackoverflow.com/questions/59677309/h2-database-json-field-hibernate-converter-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!