Issue
I use spring boot and i have an entity class like below:
@Entity
@Table(name = "form_component")
public class FormComponent implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String colSize;
private Integer colNumber;
private Integer rowNumber;
private String colAlign;
}
and on an endpoint i'd like to receive all components grouped by row number. Like so:
{
"rows": [
{
"components": [
{"rowNumber": 0, "colNumber": 0, ...},
{"rowNumber": 0, "colNumber": 1, ...}
]
},
{
"components": [
{"rowNumber": 1, "colNumber": 0, ...},
{"rowNumber": 1, "colNumber": 1, ...}
]
}
]
}
Same goes for reverse, taking above json and saving components.
How can i achieve that, any suggestions?
Solution
I might do something like this:
Define a query method in the
FormComponentRepository
that gives me all components.List components = formComponentRepository.findAll();
Then you need to group the list by
rowNumber
:Map< Integer, List> groups = components.stream().collect(groupingBy(FormComponent::getRowNumber));
You can create a class that matches the JSON structure or just use a Map, then you can populate it iterating over the
groups
Map
The reverse process is simple, iterate over the JSON structure and make batch inserts or maybe just inserts for each component.
Answered By - earandap
Answer Checked By - Mary Flores (JavaFixing Volunteer)