我正在Spring Boot中构建一个API,目的是在单个响应(一个要求)中从Oracle数据库返回每日使用数据和每月使用数据的列表。我已经设法让下面的每月和每日端点工作正常,但我很难让它们在单个响应中返回(如下面的“输出”所示)。
根据我的理解,最好的方法是创建一个服务类(AllData),它将包含每日和每月列表,然后在控制器请求(DataController)中返回它,虽然我不确定结构是什么其实在AllData& DataController类?如果我需要进一步详细说明,请告诉我。
我已经更改了这里的一些名称。
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???
}
}
输出:
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>
答案 0 :(得分:1)
你可以做到
e
或者您可以创建一个对象来包含它们而不是使用地图。请记住,这种方法需要对数据库进行两次查询。