如何不建实体类,用Mybatis将数据直接返回前端?
摘要:MySQL 统计每个时间段的数量:https:www.cnblogs.comvipsoftp19195343 在Mybatis中不建实体类,可以通过以下几种方式返回数据给前端: Mapper接口 public interface
MySQL 统计每个时间段的数量:https://www.cnblogs.com/vipsoft/p/19195343
在Mybatis中不建实体类,可以通过以下几种方式返回数据给前端:
Mapper接口
public interface VipSoftOrderMapper {
List<Map<String, Object>> getTimePeriodStatistics();
}
Mapper XML
<select id="getTimePeriodStatistics" resultType="java.util.Map">
SELECT
CONCAT(LPAD(hour_range, 2, '0'), ':00~', LPAD(hour_range + 1, 2, '0'), ':00') as timePeriod,
SUM(CASE WHEN HOUR(start_time) = hour_range THEN 1 ELSE 0 END) as startCount,
SUM(CASE WHEN HOUR(end_time) = hour_range THEN 1 ELSE 0 END) as endCount
FROM
custody_order,
(SELECT 0 as hour_range UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4
UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9
UNION SELECT 10 UNION SELECT 11 UNION SELECT 12 UNION SELECT 13 UNION SELECT 14
UNION SELECT 15 UNION SELECT 16 UNION SELECT 17 UNION SELECT 18 UNION SELECT 19
UNION SELECT 20 UNION SELECT 21 UNION SELECT 22 UNION SELECT 23) hours
GROUP BY
hour_range
ORDER BY
hour_range;
</select>
Service层
@Service
public class StatisticsService {
@Autowired
private VipSoftOrderMapper vipsoftOrderMapper;
@Autowired
private StringRedisTemplate redisTemplate;
public List<Map<String, Object>> getTimePeriodStatistics() {
List<Map<String, Object>> timePeriodStatistics = null;
String redisKey = RedisKey.TIME_PERIOD_STATISTICS + "_" + DateTime.now().year();
if (redisTemplate.hasKey(redisKey)) {
String result = redisTemplate.opsForValue().get(redisKey);
TypeReference<List<Map<String, Object>>> typeReference = new TypeReference<List<Map<String, Object>>>() {};
timePeriodStatistics = com.alibaba.fastjson.JSON.parseObject(result,typeReference);
return timePeriodStatistics;
}
timePeriodStatistics = vipsoftOrderMapper.getTimePeriodStatistics();
String redisValue = PojoUtil.pojoToJson(timePeriodStatistics);
redisTemplate.opsForValue().set(redisKey, redisValue);
redisTemplate.expire(redisKey, 1, TimeUnit.DAYS);
return timePeriodStatistics;
}
}
Controller层
@RestController
@RequestMapping("/api/statistics")
public class StatisticsController {
@Autowired
private StatisticsService statisticsService;
@GetMapping("/timePeriod")
public ResponseEntity<List<Map<String, Object>>> getTimePeriodStatistics() {
List<Map<String, Object>> result = statisticsService.getTimePeriodStatistics();
return ResponseEntity.ok(result);
}
}
前端接收的数据格式
[
{
"timePeriod": "00:00~01:00",
"startCount": 0,
"endCount": 0
},
{
"timePeriod": "01:00~02:00",
"startCount": 0,
"endCount": 0
},
{
"timePeriod": "08:00~09:00",
"startCount": 20,
"endCount": 15
},
{
"timePeriod": "09:00~10:00",
"startCount": 35,
"endCount": 19
}
// ... 其他时段
]
推荐方案
不需要创建额外的实体类
灵活性高,字段名直接在SQL中定义
Mybatis自动将结果映射到Map中
前端可以直接使用返回的数据
这样就能在不建实体类的情况下,通过Mybatis将统计数据返回给前端了。
