0
votes

(It seems to me that this question should have been already asked somewhere, but I just can't find it, so excuse me in advance if it's a duplicate)

I am using Hibernate and Gson. Say, I have an object like this

@Entity
class Foo {
    ...
    com.google.gson.JsonElement bar;
    ...
}

Foo.bar can be of arbitrary format. That's why I need to persist it in a single database field, i.e. I need to serialize it, presumably to JSON, and persist that string into the bar column of my foo table. Currently, unsurprisingly, I just get an error from Hibernate because the JsonElement type doesn't map to the string-type database column. How can I achieve this mapping (using Hibernate or, more generally, JPA)?

1
You have @AttributeConverter allowing you to convert any type to some persistable type.Neil Stockton
Thank you, that's it :)! If you post this as an answer I will accept it.DavidDuwaer

1 Answers

1
votes

You should make use of the JPA 2.1 @AttributeConverter and can then convert the JsonElement into String. It is also fully portable across other JPA providers should you ever need to use those