thanili
thanili

Reputation: 617

how to store a json object to a hibernate database field

my case is the following. I have a JSF form with three outputtexts & the corresponding inputtexts lets say:

outputtext1 - inputtext1

outputtext2 - inputtext2

outputtext3 - inputtext3

Currently i use a backbean method 'Save' in order to store them into the database (hibernate object lets say table1 with primary key table1.id) into fields table1.field1, table1.field2, table1.field3.

So each record in the table have the values inserted in the inputtexts.

My question is how am i going to store form data in the database, in a form like the following:

{"outputtext1:inputtext1","outputtext2:inputtext2"."outputtext3:inputtext3"}

and then fetch them again, parse and rebuild the form. I am thinking of manipulating form data as JSON object... But i am new to both Java+JSON so some guideliness would be really useful for me!

This is an indicative example, form are going to by dynamic and created on the fly.

Upvotes: 5

Views: 14607

Answers (4)

Aditya Singh
Aditya Singh

Reputation: 48

change hibernate-mapping like this JSONObject obj = new JSONObject(stringRepresentationOfJSON);

Upvotes: -2

Fritz
Fritz

Reputation: 10045

Why would you want to serialize/deserialize a JSON to send it directly to the database? Deserialization has its own issues and multiple deserializations could (not will) be a source of issues.

You should save the fields as attributes from a given entity and then, with the help of libraries like Gson, generate the JSON from the entity.


Update

Since your form is dynamic, you can use some adaptable entity structure to hold your data.

Your entities can either have a Map<String,String> attribute or a collection of, say, FieldRecord entities that contain a key - value pair.

I suggest this because a JSON in the database can lead to complex issues, in particular if you'll have to query that data later. YOu'll have to process the JSONs in order to either report or find which records have a particular field. This is just an example, things can get more complex.

Upvotes: 4

rai.skumar
rai.skumar

Reputation: 10667

Convert JSONObject into a Stringform and then store. And when your read it back, convert it back into JSONObject like below :

       JSONObject obj = new JSONObject(stringRepresentationOfJSON);

Upvotes: 1

Stephan
Stephan

Reputation: 8090

Simple, you need a BLOB type column in your table to store the json and when you retrieve it in java you just need to decode the json and i recomend using https://code.google.com/p/json-simple/ its very simple

Upvotes: 2

Related Questions