1.引入相关依赖
<!-- fastjson --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>${fastjson.version}</version> </dependency> <!--mybatisplus--> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>${mybatisplus.version}</version> </dependency> <!--lombok--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency>
2.我们以查询商品的名称,数量为例做一个饼状图
NameNumber.java
@Data @AllArgsConstructor @NoArgsConstructor public class NameNumber { @JsonProperty("value") //echarts 要求返回的名称,要不封装不上数据 private int number; @JsonProperty("name") //echarts 要求返回的名称,要不封装不上数据 private String goodsname; }
3.PieVo.java 用来返回json数据的实体,里面装着List<NameNumber>
@Data @NoArgsConstructor @AllArgsConstructor public class PieVo { private List<NameNumber> nameNumberList; }
4.EchartsController.java
@RestController @RequestMapping("/echarts") public class EchartsController { @Autowired PieMapper pieMapper; @RequestMapping("/pie") public PieVo loadAll(){ PieVo pieVo = new PieVo(); List<NameNumber> pieVoList = pieMapper.findNameNumber(); pieVo.setNameNumberList(pieVoList); return pieVo; } }
5.PieMapper.java
@Mapper public interface PieMapper { @Select("select goodsname,number from bus_goods") public List<NameNumber> findNameNumber(); }
6.echarts饼图页面
<!DOCTYPE html> <html xmlns:th="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8"> <script type="text/javascript" th:src="@{/echarts/jquery.min.js}"></script> </head> <body> <div class="page-container" id="main" style="width: 95%;height:580px;"></div> <script type="text/javascript" th:src="@{/echarts/echarts.js}"></script> <script type="text/javascript"> // 基于准备好的dom,初始化echarts实例 var myChart = echarts.init(document.getElementById('main')); $.ajax({ //你需要写这些请求 异步请求数据 type: "GET", url: "/echarts/pie", dataType: 'json', success: function (data) { // 指定图表的配置项和数据 option = { title: { text: '商品数量展示', subtext: '北京地区', x: 'center' }, tooltip: { trigger: 'item', formatter: "{a} <br/>{b} : {c} ({d}%)" }, // legend: { // orient: 'vertical', // left: 'left', // data: data.nameNumberList.goodsname // }, series: [ { name: '商品数量', type: 'pie', radius: '55%', center: ['50%', '60%'], data: data.nameNumberList,//json实体的list数据 itemStyle: { emphasis: { shadowBlur: 10, shadowOffsetX: 0, shadowColor: 'rgba(0, 0, 0, 0.5)' } } } ] }; // 使用刚指定的配置项和数据显示图表。 myChart.setOption(option); } }); /** */ </script> </body> </html>