I'm building an API in Spring Boot with the goal of returning a list of daily usage data and monthly usage data from an Oracle database in a single response (a requirement). I've managed to get the below working with both monthly and daily endpoints okay but I'm struggling to get them to return in a single response (as shown in "output" below).
From my understanding the best way of doing this is to create a service class (AllData) which will contain both daily and monthly lists and then return that in the controller request (DataController) although I'm not sure on what the structure of that actually looks like in AllData & DataController? Let me know if I need to elaborate on this further.
I have changed some of the names around here for the example.
MonthlyData.java
@Entity
@Table(schema = "TEST", name = "MONTHLYDATA")
public class MonthlyData {
@Id
private long id;
private String username;
private String month;
private Integer usage;
public MonthlyData(){
}
public String getUserName(){
return username;
}
public String getMonth(){
return month;
}
public Integer getUsage(){
return usage;
}
}
DailyData.java
@Entity
@Table(schema = "TEST", name = "DAILYDATA")
public class DailyData {
@Id
private long id;
private String username;
private String date;
private Integer usage;
public DailyData(){
}
public String getUserName(){
return username;
}
public String getDate(){
return date;
}
public Integer getUsage(){
return usage;
}
}
MonthlyDataRepository.java
// Populates a list of MonthlyData from the Oracle database
public interface MonthlyDataRepository extends PagingAndSortingRepository<MonthlyData, String> {
List<MonthlyData> findByUserName(String username);
}
DailyDataRepository.java
// Populates a list of DailyData from the Oracle database
public interface DailyDataRepository extends PagingAndSortingRepository<DailyData, String> {
List<DailyData> findByUserName(String username);
}
AllData.java
@Service("AllData")
public class AllData {
@Autowired
DailyDataRepository dailyDataRepository;
@Autowired
MonthlyDataRepository monthlyDataRepository;
// Something to combine and return both Daily and Monthly data lists
public List <DailyData> readDailyData(String username) {
return dailyDataRepository.findByUserName(username);
}
public List <MonthlyData> readMonthlyData(String username) {
return monthlyDataRepository.findByUserUserName(username);
}
}
DataController.java
@RestController()
@RequestMapping("/data")
public class DataController {
@RequestMapping(path = "{username}", method = RequestMethod.GET)
public List <AllData> readAllData(@PathVariable String username) {
// Return the AllData list here???
}
}
Output:
http://localhost:8080/data/dave
<List>
<item>
<date>11122017</date>
<usage>24562</usage>
</item>
<item>
<date>10122017</date>
<usage>123546</usage>
</item>
</List>
<List>
<item>
<month>November</month>
<usage>6745234634</usage>
</item>
<item>
<month>December</month>
<usage>242346</usage>
</item>
</List>