1

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;
        }
    }
}
Sha
  • 921
  • 17
  • 46

1 Answers1

2

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"}]'
Evgenij Ryazanov
  • 6,960
  • 2
  • 10
  • 18