I want to save data in MYSQL DB by creating Entity class and repository from scratch. I am able to save the normal String Data, Integer Data but struggling to save complex JSON data's
for instance:
[
{
"id": "0001",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"batters":
{
"batter":
[
{ "id": "1001", "type": "Regular" },
{ "id": "1002", "type": "Chocolate" },
{ "id": "1003", "type": "Blueberry" },
{ "id": "1004", "type": "Devil's Food" }
]
},
"topping":
[
{ "id": "5001", "type": "None" },
{ "id": "5002", "type": "Glazed" },
{ "id": "5005", "type": "Sugar" },
{ "id": "5007", "type": "Powdered Sugar" },
{ "id": "5006", "type": "Chocolate with Sprinkles" },
{ "id": "5003", "type": "Chocolate" },
{ "id": "5004", "type": "Maple" }
]
},
{
"id": "0002",
"type": "donut",
"name": "Raised",
"ppu": 0.55,
"batters":
{
"batter":
[
{ "id": "1001", "type": "Regular" }
]
},
"topping":
[
{ "id": "5001", "type": "None" },
{ "id": "5002", "type": "Glazed" },
{ "id": "5005", "type": "Sugar" },
{ "id": "5003", "type": "Chocolate" },
{ "id": "5004", "type": "Maple" }
]
},
{
"id": "0003",
"type": "donut",
"name": "Old Fashioned",
"ppu": 0.55,
"batters":
{
"batter":
[
{ "id": "1001", "type": "Regular" },
{ "id": "1002", "type": "Chocolate" }
]
},
"topping":
[
{ "id": "5001", "type": "None" },
{ "id": "5002", "type": "Glazed" },
{ "id": "5003", "type": "Chocolate" },
{ "id": "5004", "type": "Maple" }
]
}
]
How can I store such JSON's in MYSQL Db?
Should I Create Class for every nested element ?
(I would consider to switch to a NoSQL DB instead of MySQL, but okay...)
//1.
create table users_json(
id int auto_increment primary key,
details json);
2.
public interface SomeRepository extends JpaRepository<AnyEntity, Long> {
#Modifying(clearAutomatically = true)
#Query(value = "insert into users_json (details) values (:param) ", nativeQuery = true)
#Transactional
int insertValue(#Param("param") String param);}
3.
anyRepository.insertValue("{ \"page\": \"1\" , \"name\": \"Zafari\", \"os\": \"Mac\", \"spend\": 100, \"resolution\": { \"x\": 1920, \"y\": 1080 } }");
4.
SELECT id, details->'$.name' FROM users_json;
Storing JSON in MySQL is possible. You can use these 3 column types depending upon the column size.
For your Entity class :
#Entity
#Getter
#Setter
public class Test {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#Column(columnDefinition = "LONGTEXT") // can store upto 4GB
private String longText;
#Column(columnDefinition = "MEDIUMTEXT") // can store upto 64MB
private String mediumText;
#Column(columnDefinition = "TEXT") // can store upto 64KB
private String text;
}
For your Controller method :
#PostMapping(value = "/addData")
public void addData(#RequestBody String payload) {
testRepository.addData(payload);
}
For your Repository Class:
#Repository
public interface TestRepository extends JpaRepository<Test,Integer> {
#Modifying
#Transactional
#Query(value = "INSERT INTO test(text,medium_text,long_text) VALUE(?1,?1,?1)" ,nativeQuery = true)
void addData(String payload);
}
In MYSQL it will look like this,
It depends if you want to store your Json as String or do you want to convert it into DTO instances that are mapped to your entities and use repository to save them to DB? If you want to store JSON as a String than It shouldn't be any different from any other String. If you want to store it as Entities than you need to convert your JSON (de-serialize) into your DTOs and then work with them as regular DTOs. It doesn't matter how they where created. I just answered very similar question. Please see here
I have a complex issue here and some advice or suggestions would be greatly appreciated. Essentially I have a complex JSON schema that looks something like this:
{
"$schema": "http://example.org",
"$id": "http://example.org",
"title": "schema title",
"description": "description",
"properties": {
"name": {
"description": "description",
"type": "string",
"enum": [
"name1",
"name2"
]
},
"storage": {
"description": "description",
"type": "integer",
"minimum": "200",
"maximum": "500",
"default": "200",
},
"domain": {
"description": "description",
"type": "string"
},
},
"if": {
"properties": {
"name": {
"const": "name1"
}
}
},
"then": {
"if": {
"properties": {
"version": {
"const": "version1"
}
}
},
"then": {
"properties": {
"cpus": {
"description": "description",
"type": "integer",
"minimum": 1,
"maximum": 8
},
"memory": {
"description": "description",
"type": "integer",
"minimum": 1,
"maximum": 32
},
},
"required": [
"cpus",
"memory"
]
},
"else": {
"if": {
"properties": {
"version": {
"const": "version2"
}
}
},
"then": {
"properties": {
"cpus": {
"description": "description",
"type": "integer",
"minimum": 1,
"maximum": 8
},
"diskSize": {
"description": "description",
"type": "integer",
"minimum": 250,
"maximum": 1000
},
},
"required": [
"cpus",
"diskSize"
]
}
}
},
"else": {
"if": {
"properties": {
"name": {
"const": "name2"
}
}
},
"then": {
"if": {
"properties": {
"version": {
"const": "version3"
}
}
},
"then": {
"properties": {
"diskSize": {
"description": "description",
"type": "integer",
"minimum": 100,
"maximum": 500
}
"memory": {
"description": "description",
"type": "integer",
"minimum": 1,
"maximum": 28
}
},
"required": [
"diskSize",
"memory"
]
},
"else": {
"if": {
"properties": {
"version": {
"const": "version4"
}
}
},
"then": {
"properties": {
"cpus": {
"description": "description",
"type": "integer",
"minimum": 1,
"maximum": 28
},
"memory": {
"description": "description",
"type": "integer",
"minimum": 1,
"maximum": 64
}
},
"required": [
"cpus",
"memory"
]
}
}
}
}
}
I need to build a JSON object using this schema in java. Every property in the schema is inside of a map that I have access to, so I can quite simply just get the property from the map and add it to a JsonNode object that I am building. Every property under the initial "properties" object is easy to retrieve, I can just get a list of them and then get each one from the map.
The complexity lies in the if/then/else part of the json schema. The only way I can see to find which property I need is to first build the initial part of the json from the first "properties" object and then have some sort of quite complex recursive algorithm that goes into every if/then/else statement and compares the value of the property being evaluated and then returns a list of the properties I need to get from the map. I have looked around online for a library that can build Json from a Json schema in java but haven't found anything that can deal with the complex if/then/else statements.
Any suggestions or ideas would be greatly appreciated.
I have one abstract class and three other subclass. I would like those three subclasses as example on the Swagger/OpenAPI interface.
But the Swagger/OpenApi interface show just the abstract class and the first subclass fields.
OperationRequest
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "subType", visible = true)
#JsonSubTypes({
#JsonSubTypes.Type(value = InstallmentOperationRequest.class, name = "I"),
#JsonSubTypes.Type(value = CreditCardOperationRequest.class, name = "C"),
#JsonSubTypes.Type(value = SingleOperationRequest.class, name = "S")
})
#Schema(
description = "Parent operation request",
discriminatorProperty = "subType",
discriminatorMapping = {
#DiscriminatorMapping(value = "SingleOperation", schema = SingleOperationRequest.class),
#DiscriminatorMapping(value = "InstallmentOperation", schema = InstallmentOperationRequest.class),
#DiscriminatorMapping(value = "CreditCardOperation", schema = CreditCardOperationRequest.class)
})
public abstract class OperationRequest {
private String description;
private OperationTypeEnum type;
private OperationSubTypeEnum subType;
private BigDecimal value;
private String observations;
}
CreditCardOperationRequest
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonTypeName("C")
#Schema(allOf = OperationRequest.class)
public class CreditCardOperationRequest extends OperationRequest {
private String creditCard;
private LocalDate creditCardOperationDate;
private Integer creditCardInstallments;
}
SingleOperationRequest
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonTypeName("S")
#Schema(allOf = OperationRequest.class)
public class SingleOperationRequest extends OperationRequest{
private BigDecimal paidValue;
private YearMonth period;
}
InstallmentOperationRequest
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonTypeName("I")
#Schema(allOf = OperationRequest.class)
public class InstallmentOperationRequest extends OperationRequest{
private Integer installments;
private YearMonth initialInstallment;
}
Json generated
...
"components": {
"schemas": {
"CreditCardOperationRequest": {
"required": [
"creditCard",
"creditCardInstallments",
"description",
"subType",
"type",
"value"
],
"type": "object",
"allOf": [
{
"$ref": "#/components/schemas/OperationRequest"
},
{
"type": "object",
"properties": {
"creditCard": {
"type": "string",
"description": "Credit card identification",
"example": "abcd"
},
"creditCardOperationDate": {
"type": "string",
"description": "Credit card operation date",
"format": "date",
"example": "2021-01-10"
},
"creditCardInstallments": {
"minimum": 1,
"type": "integer",
"description": "Number of credit card installments",
"format": "int32",
"example": 5
}
}
}
]
},
"InstallmentOperationRequest": {
"required": [
"description",
"initialInstallment",
"installments",
"subType",
"type",
"value"
],
"type": "object",
"allOf": [
{
"$ref": "#/components/schemas/OperationRequest"
},
{
"type": "object",
"properties": {
"installments": {
"minimum": 2,
"type": "integer",
"description": "Number of installments",
"format": "int32",
"example": 5
},
"initialInstallment": {
"type": "string",
"description": "Initial installment period",
"example": "2021-01"
}
}
}
]
},
"OperationRequest": {
"required": [
"description",
"subType",
"type",
"value"
],
"type": "object",
"properties": {
"description": {
"type": "string",
"description": "Operation description",
"example": "abc"
},
"type": {
"type": "string",
"description": "Operation type",
"enum": [
"I",
"E"
]
},
"subType": {
"type": "string",
"description": "Operation subType",
"enum": [
"S",
"C",
"I"
]
},
"value": {
"type": "number",
"description": "Operation value",
"format": "double",
"example": 32.56
},
"observations": {
"maxLength": 2147483647,
"minLength": 2,
"type": "string",
"description": "Observations",
"example": "abc"
}
},
"description": "Parent operation request",
"discriminator": {
"propertyName": "subType"
}
},
"SingleOperationRequest": {
"required": [
"description",
"paidValue",
"subType",
"type",
"value"
],
"type": "object",
"allOf": [
{
"$ref": "#/components/schemas/OperationRequest"
},
{
"type": "object",
"properties": {
"paidValue": {
"type": "number",
"description": "Operation paid value",
"example": 12.56
},
"period": {
"type": "string",
"description": "Operation period",
"example": "2021-01"
}
}
}
]
}
...
}
}
...
enter image description here JSON Response:-
{
"hotelogix": {
"version": "1.0",
"datetime": "2017-01-17T11:37:58",
"response": {
"status": {
"code": 0,
"message": "success"
},
"nightAuditDate": "2015-04-15",
"lastUpdatedOn": "2017-01-17 11:05:40",
"isUpdated": true,
"totalRecords": "2",
"totalPages": 1,
"bookings": [
{
"isGroup": false,
"group": null,
"id": "gbighAuuug||",
"mainId": "gbighAuuug||",
"checkInDate": "2015-04-15",
"checkOutDate": "2015-04-16",
"adult": 2,
"child": 0,
"infant": 0,
"code": "12281852",
"reservationStatus": "RESERVE",
"businessSourcesId": null,
"source": "PMS",
"preference": "",
"roomStays": [
{
"date": "2015-04-15",
"roomTypeId": "gb_BTEs|",
"roomTypeName": "old age rooms",
"roomTypeCode": "CLSccc",
"roomId": "0",
"roomName": "",
"rateId": "gw||",
"rateName": "Seasonal Rate",
"amount": "600.000000",
"tax": "0.000000",
"discountAmount": "0.000000"
}
],
"guestStays": [
{
"id": "h2H4TkT2Bw||",
"mainId": "h2H4TkT2Bw||",
"checkInDate": "2015-04-15",
"checkOutDate": "2015-04-16",
"status": "RESERVE",
"isPrimary": true,
"isChargeSharer": true,
"type": "Adult",
"guestDetails": {
"id": "gsgPzJITYA||",
"code": "P949",
"salutation": null,
"fName": "Neha",
"lName": "Sharma",
"email": "neha#hotelogix.com",
"phoneNo": "55887799",
"mobileNo": "",
"gender": null,
"nationality": null,
"identityTypeId": null,
"identityNo": null,
"isBlackList": false,
"isVip": false,
"dob": "-0001-11-30",
"organization": null,
"designation": null,
"spouseSalutation": null,
"spouseFName": null,
"spouseLName": null,
"spouseDob": "0000-00-00 00:00:00",
"anniversary": "0000-00-00 00:00:00",
"addresses": {
"home": {
"address": "",
"country": null,
"state": null,
"city": "",
"zip": "",
"fax": null
},
"work": {
"address": "",
"country": null,
"state": null,
"city": "",
"zip": "",
"fax": null,
"phone": null,
"mobile": null
}
},
"files": []
}
},
{
"id": "h2H4TkT2Ag||",
"mainId": "h2H4TkT2Ag||",
"checkInDate": "2015-04-15",
"checkOutDate": "2015-04-16",
"status": "RESERVE",
"isPrimary": false,
"isChargeSharer": false,
"type": "Adult",
"guestDetails": {
"id": "gsgPzJITYg||",
"code": "P951",
"salutation": null,
"fName": "Mayajhanti",
"lName": "Jha",
"email": "mayanti#hotelogix.com",
"phoneNo": "01158988888",
"mobileNo": "99680480558",
"gender": "Male",
"nationality": "US",
"identityTypeId": null,
"identityNo": null,
"isBlackList": false,
"isVip": false,
"dob": "-0001-11-30",
"organization": null,
"designation": null,
"spouseSalutation": null,
"spouseFName": null,
"spouseLName": null,
"spouseDob": "0000-00-00 00:00:00",
"anniversary": "0000-00-00 00:00:00",
"addresses": {
"home": {
"address": "D-996, Cross Road",
"country": "US",
"state": "CA",
"city": "Los Angeles",
"zip": "325215",
"fax": null
},
"work": {
"address": "",
"country": null,
"state": null,
"city": "",
"zip": "",
"fax": null,
"phone": null,
"mobile": null
}
},
"files": [
{
"name": "Id Proof",
"url": "c://Users//mukesh//Desktop//abc.png"
},
{
"name": "Id Proof",
"url": "c://Users//mukesh//Desktop//abc.png"
}
]
}
}
],
"payments": [],
"otherCharges": [],
"addons": [],
"isHoldTill": false,
"releaseDate": "0000-00-00 00:00:00"
},
{
"isGroup": true,
"group": {
"id": "h2AIqHf1",
"mainId": "h2AIqHf1",
"checkInDate": "2015-04-15",
"checkOutDate": "2015-04-16",
"code": "G 0117433",
"groupStatus": "RESERVE",
"businessSourcesId": null,
"source": "",
"preference": "",
"ownerType": "Guest",
"owner": {
"id": "gsgPzf2HQw||",
"code": "P957",
"salutation": null,
"fName": "juna",
"lName": "mishra",
"email": "juna#hotelogix.com",
"phoneNo": "",
"mobileNo": "8802640811",
"gender": null,
"nationality": null,
"identityTypeId": null,
"identityNo": null,
"isBlackList": false,
"isVip": false,
"dob": "-0001-11-30",
"organization": null,
"designation": null,
"spouseSalutation": null,
"spouseFName": null,
"spouseLName": null,
"spouseDob": "0000-00-00 00:00:00",
"anniversary": "0000-00-00 00:00:00",
"addresses": {
"home": {
"address": "",
"country": null,
"state": null,
"city": "",
"zip": "",
"fax": null
},
"work": {
"address": "",
"country": null,
"state": null,
"city": "",
"zip": "",
"fax": null,
"phone": null,
"mobile": null
}
},
"files": []
},
"payTerm": 2,
"payments": [],
"otherCharges": [],
"groupLeader": []
},
"id": "gbihNuZBbA||",
"mainId": "gbihNuZBbA||",
"checkInDate": "2015-04-15",
"checkOutDate": "2015-04-16",
"adult": 1,
"child": 0,
"infant": 0,
"code": "01171859",
"reservationStatus": "RESERVE",
"businessSourcesId": null,
"source": "PMS",
"preference": "",
"roomStays": [
{
"date": "2015-04-15",
"roomTypeId": "gb_BTEs|",
"roomTypeName": "old age rooms",
"roomTypeCode": "CLSccc",
"roomId": "0",
"roomName": "",
"rateId": "gw||",
"rateName": "Seasonal Rate",
"amount": "500.000000",
"tax": "0.000000",
"discountAmount": "0.000000"
}
],
"guestStays": [
{
"id": "h2ANlxcGFg||",
"mainId": "h2ANlxcGFg||",
"checkInDate": "2015-04-15",
"checkOutDate": "2015-04-16",
"status": "RESERVE",
"isPrimary": true,
"isChargeSharer": true,
"type": "Adult",
"guestDetails": {
"id": "gsgPzf2HQg||",
"code": "P958",
"salutation": null,
"fName": "mina",
"lName": "sharma",
"email": "",
"phoneNo": "545487875454",
"mobileNo": "",
"gender": "Male",
"nationality": null,
"identityTypeId": null,
"identityNo": null,
"isBlackList": false,
"isVip": false,
"dob": "-0001-11-30",
"organization": null,
"designation": null,
"spouseSalutation": null,
"spouseFName": null,
"spouseLName": null,
"spouseDob": "0000-00-00 00:00:00",
"anniversary": "0000-00-00 00:00:00",
"addresses": {
"home": {
"address": "",
"country": null,
"state": null,
"city": "",
"zip": "",
"fax": null
},
"work": {
"address": "",
"country": null,
"state": null,
"city": "",
"zip": "",
"fax": null,
"phone": null,
"mobile": null
}
},
"files": []
}
}
],
"payments": [],
"otherCharges": [],
"addons": [],
"isHoldTill": false,
"releaseDate": "0000-00-00 00:00:00"
}
]
},
{
"xyx": {
"version": "1.0",
"datetime": "2016-12-13T05:27:08",
"response": {
"status": {
"code": 0,
"message": "success"
},
"hotels": [
{
"id": 6209,
"userTypes": [
{
"id": "UXjk0A||",
"title": "manager",
"status": "Active"
},
{
"id": "UJlhsA||",
"title": "test23",
"status": "Active"
},
{
"id": "UJll-Q||",
"title": "march",
"status": "Active"
},
{
"id": "UJlnNA||",
"title": "ajay mishra",
"status": "Active"
},
{
"id": "UJlnMw||",
"title": "prime",
"status": "Active"
},
{
"id": "UJlnPg||",
"title": "rr",
"status": "Active"
},
{
"id": "UJlnPw||",
"title": "xman",
"status": "Active"
},
{
"id": "UJloKg||",
"title": "sdd",
"status": "Active"
},
{
"id": "UJloKQ||",
"title": "tst1",
"status": "Active"
},
{
"id": "UJloLg||",
"title": "test2",
"status": "Active"
},
{
"id": "UJloLw||",
"title": "test3",
"status": "Active"
},
{
"id": "UJlpoA||",
"title": "kk",
"status": "Active"
},
{
"id": "UJlpqQ||",
"title": "shantanu manager",
"status": "Active"
},
{
"id": "UJhGcA||",
"title": "elbo",
"status": "Active"
}
]
}
]
},
"request": {
"method": "getusertypes",
"key": "02w7TK3e-0Ccoyo",
"data": {
"hotels": [
{
"id": 6209
}
]
}
}
}
}
My code:-
String getusertypestitlestring = jsonResult.getJSONObject("xyz").getJSONObject("response").getJSONArray("hotels").getJSONArray(0).getString(1);
:: i want to get userTypes>> title
:: i want to get bookings >> group >> code
Try this:
JSONArray userTypesArray = jsonResult.getJSONObject("xyx").getJSONObject("response").getJSONArray("hotels").getJSONObject(0).getJSONArray("userTypes");
for(int i =0 ; i< userTypesArray.length(); i++){
JSONObject userType = userTypesArray.getJSONObject(i);
System.out.println(userType.get("title"));
}
String getusertypestitlestring = jsonResult.getJSONObject("xyz").getJSONObject("response").getJSONArray("hotels").getJSONArray(0).getString(1);
Here it is not xyz, that is xyx
Make pojo of each Json Object in your Json String.
For Ex:
Make class POJO:
public class POJO {
XYX xyx;
public XYX getXyx() {
return xyx;
}
public void setXyx(XYX xyx) {
this.xyx = xyx;
}
}
Make class XYX:
public class XYX implements Serializable{
String version;
String datetime;
Response response;
Request request;
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getDatetime() {
return datetime;
}
public void setDatetime(String datetime) {
this.datetime = datetime;
}
public Response getResponse() {
return response;
}
public void setResponse(Response response) {
this.response = response;
}
public Request getRequest() {
return request;
}
public void setRequest(Request request) {
this.request = request;
}
}
Make class Response:
class Response {
Status status;
List<Hotels> hotels;
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public List<Hotels> getHotels() {
return hotels;
}
public void setHotels(List<Hotels> hotels) {
this.hotels = hotels;
}
}
Make Class Request :
class Request {
String method;
String key;
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
}
and for List
Make class Hotels:
class Hotels {
String id;
List<UserTypes> userTypes;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public List<UserTypes> getUserTypes() {
return userTypes;
}
public void setUserTypes(List<UserTypes> userTypes) {
this.userTypes = userTypes;
}
}
and make all other pojo classes and use Gson library to set data in your pojos :
POJO pojo = new Gson().fromJson(jsonResponse,POJO.class);
And read Data from pojo :
System.out.println(pojo.getXyx().getDatetime());
System.out.println(pojo.getXyx().getRequest().getKey());
System.out.println(pojo.getXyx().getResponse().getHotels().get(0).getUserTypes().get(0).getTitle());
You can easily use GSON instead of JSON. It's more comfortable to work with the GSON objects. More input is available at:
https://google.github.io/gson/apidocs/com/google/gson/Gson.html