I am new to Spring data and mongodb. I have a JSON object which represents a JSON Schema and I need to store that in mongodb using spring data. But the issue with JSON schema is the structure of JSON Schema is dynamic; for example below are two valid JSON schema with completely different structure.
{
"type": "object",
"properties": {
"name": {
"type": "string",
"minLength": 10
},
"age": {
"type": "integer"
}
},
"required": [
"name",
"age"
]
}
{
"type": "array",
"items": {
"type": "object",
"properties": {
"abc": {
"type": "boolean"
},
"xyz": {
"$ref": "#/definitions/"
},
"asd": {
"type": "null"
}
},
"required": [
"abc",
"xyz"
]
}
}
How can I define a JAVA POJO Class so that I can map the above JSON with the defined class and store it in mongodb. Or is it possible to do CURD operation in spring without mapping it to a POJO class?
Please find here the necessary code.
Here is my repository class
And here is a controller snippet which u can use to try it out
This is how it looks like in Mongo after save.
In my project I had a very dynamic structure of my models and I mapped them by using a
java.util.Map
objectthis is how my mondo document model has been implemented:
By using this all works pretty good
You can map embedded documents using
@DBref
http://www.baeldung.com/cascading-with-dbref-and-lifecycle-events-in-spring-data-mongodb
http://docs.spring.io/spring-data/data-mongo/docs/1.4.2.RELEASE/reference/html/mapping-chapter.html#mapping-usage-references
Or as Angelo Immediata suggested
And you will need some custom read and write converters
http://docs.spring.io/spring-data/data-mongo/docs/1.4.2.RELEASE/reference/html/mapping-chapter.html#mapping-explicit-converters
I would recommend using MongoTemplate and serialize and deserailize using Gson/Jackson.
Mongo Template have CRUD methods which takes collection name and DBObject entity which is very similar to if you were to directly use mongo java driver.
So you will have json payload and using one of the mapper library to convert them into
Map
.Something like
Deserialise
DBObject
MongoTemplate
You can do something similar for all other CRUD operations.
FWIW, MongoDB 3.6 introduced JSON Schema Validation support at the database level. You can read more on MongoDB's blog. Hope that helps a bit!