I am requesting data using RestTemplate and get a JSON Object.
I want to insert this data into a relational database. My thoughts after I have been reading was to convert this to java records. It is a nested JSON Object where I want to insert the different levels into different tables.
I am building this project using Sping Boot,
I would like to insert the the following data:
id, owner, model, year into a table namned cars
and then I want to insert the events inte an event table. type, cost, date into a table namned events
{
"meta": {
"total_count": 2,
"current_count": 2,
"per_page": 10,
"start": 1,
"end": 2,
"current_page": 1,
"page_count": 1
},
"data": [
{
"id": 1,
"owner": "Charles John",
"model": "Volvo,
"year": 2020
"services": {
"events": [
{
"type": "repair",
"cost": 1000
"date": "2022-01-12"
},
{
"type": "cleaning",
"cost": 200
"date": "2022-01-15"
},
{
"type": "washing",
"cost": 100
"date": "2022-03-05"
}
]
}
},
{
"id": 2,
"owner": "John Carlsson",
"model": "Mercedes,
"year": 2021
"services": {
"events": [
{
"type": "repair",
"cost": 4000
"date": "2022-02-12"
},
{
"type": "cleaning",
"cost": 200
"date": "2022-02-27"
}
]
}
}
]
}
My RestTemplate looks something similar to this:
public void getCarEvents() {
RestTemplate rt = new RestTemplate();
HttpEntity<?> request = createAuth();
String result = restTemplate.getForObject(buildUri("/cars").toString(), String.class);
ResponseEntity<CarsResponse> carsResponse = restTemplate.exchange(result, HttpMethod.GET, request, new ParameterizedTypeReference<CarsResponse> {});
List<CarsResponse> response = carsResponse.getBody();
...
...
...
}
Where CarsResponse looks something like this:
public record CarsResponse(
Meta meta;
ArrayList<Car> data
) {}
whre Car looks like this:
public record Car(
int id,
String name,
int age,
Services services
) {}
public record Services(
ArrayList<Event> events
) {}
public record Event (
String type,
int cost,
String date,
){}
Should I also make a class for Car and Event like the following?
@Entity
@Table(name = "event")
public class Event{
@Column(name = "type")
private String type;
@Column(name = "cost")
private int cost;
@Column(name = "date")
private String date;
//Getter, Setter, Constructor, toString()
}
I have only found example where they have more simple JSON Object and not found any with a nested version. Where do I go from here. How do I only get the data from Event so I only insert this data into that table?
Also I would like to get the Id from Car inserted into the Event table to so I now for which car the event has been done for.