Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to store a json object to a hibernate database field

Tags:

java

json

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.

like image 499
thanili Avatar asked Apr 05 '13 14:04

thanili


People also ask

Can you store JSON in a database?

You can store JSON documents in SQL Server or SQL Database and query JSON data as in a NoSQL database.

Does hibernate support JSON?

The Hibernate Types support for JSON column mapping is very useful, and you can use it to map entity attributes that are either POJO, String , or even JsonNode . The best thing about the Hibernate Types project is that it offers support for Oracle, SQL Server, PostgreSQL, or MySQL JSON column types.

How do I persist JSON?

The most basic way to persist a JSON object in a relational database is to convert the object into a String before persisting it. Then, we convert it back into an object when we retrieve it from the database.


1 Answers

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.

like image 157
Fritz Avatar answered Oct 19 '22 22:10

Fritz