Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there anything for hibernate that serialize/deserialize a json(or xml) column converting it into real model attributes?

Tags:

java

hibernate

In Rails we have the serialize method, which takes an attribute(or column) that will be automagically serialized into json when saved in the database.

After that object is saved and queried, the object serialized json can be accessible as real class attributes.

My question is: is there anything build-in or a package that adds this feature to hibernate? If negative, is it possible to create attributes dynamically with the reflection java api?

I'm questioning this because I'm kinda interest into studying a little of Java and what you can do with the JVM.

Thanks.

like image 816
thiagofm Avatar asked Nov 12 '12 18:11

thiagofm


2 Answers

I don't really understand what you want, sorry.

But if you want to have a field of an object whose value saved to the database in a serialized form in a single column, rather than being mapped to reference to a row in another table, then that's a standard part of JPA. You simply define a field, then don't annotate it with a relationship annotation. I believe the type of the field has to be a subtype of Serializable, though (sadly). For example:

@Entity
public class Colleague {
    @Id
    private int id;
    private HashMap<Date, String> diary;
}

That will map to a table like this:

create table Colleague (
    id integer primary key,
    diary blob
)

Now, you mentioned JSON. This won't use JSON; it will use standard Java serialization. I don't think there's any particularly sane way to make it use JSON instead; the easiest would probably be to wrap the object to be serialized in JSONifying wrapper. Not too hard, but a bit weird.

Still, even though this isn't JSON, it is useful in much the same way: data goes into the database and then comes back out.

Again, no idea if this is really what you want, sorry!

like image 101
Tom Anderson Avatar answered Oct 15 '22 12:10

Tom Anderson


You can write your own custom user type for this using existing JSON libraries like Jackson or Gson.

  1. jackson-hibernate-module: Pre-existing library based on Jackson. Supports the notion of lazy loading
  2. Creating custom JSON user type.
like image 21
Aravind Yarram Avatar answered Oct 15 '22 10:10

Aravind Yarram