Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using JPA and JSON serialization

Tags:

java

json

jpa

I would like to have a JPA Entity that has a GSon Object as a field/attribute. For instance:

@Entity
public class MyEntity {

    private JsonObject myObject;

    public JsonObject getObject() {
        return myObject;
    }

    public void setObject(JsonObject obj) {
        myObject = obj;
    }

}

I'm not familiar with how the persistence manager will persist these. Ideally it would be as a JSON string, but essentially what I want to do is hide how things are persisted from the public API. I could do this potentially with an inner class that has methods like String getObject() that my outer class delegates to and does the JSON parse to return a JsonObject, but I'm wondering if there's another way.

like image 353
Anon Avatar asked Feb 02 '26 14:02

Anon


2 Answers

It may be prudent to just store them as Strings (varchars) in the db. Just perform the GSon serialize / deserialize in your manager or dao.

like image 91
Paul Gregoire Avatar answered Feb 05 '26 03:02

Paul Gregoire


If JsonObject implements Serializable, then it should behave correctly, but depending on how that class is written, it's possible that you'll wind up storing a lot of cruft you don't need. Converting it to a string seems like the preferable solution.

Possibly related: Combining JAXB and JPA in one model

like image 38
Mike Baranczak Avatar answered Feb 05 '26 04:02

Mike Baranczak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!