mybatisplus代码生成器 echarts
时间: 2025-04-21 18:44:42 浏览: 20
### 使用 MyBatisPlus 代码生成器并集成 ECharts
#### 创建 MyBatisPlus 代码生成器配置类
为了使用 MyBatisPlus 的代码生成功能,需创建一个自定义的 `GeneratorConfig` 类来设置数据库连接和其他必要参数。
```java
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
public class GeneratorConfig {
public static void main(String[] args) {
AutoGenerator mpg = new AutoGenerator();
// 设置全局配置
GlobalConfig gc = new GlobalConfig();
String projectPath = System.getProperty("user.dir");
gc.setOutputDir(projectPath + "/src/main/java");
gc.setAuthor("Your Name");
gc.setOpen(false);
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://localhost:3306/your_database?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC");
dsc.setDriverName("com.mysql.cj.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("password");
mpg.setDataSource(dsc);
// 包名策略配置
PackageConfig pc = new PackageConfig();
pc.setParent("com.example");
pc.setModuleName(null); // 不指定模块名称,默认会根据表前缀自动识别
mpg.setPackageInfo(pc);
// 表策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setInclude("table_name"); // 需要生成哪些表
strategy.setNaming(mp.NameType.CAMEL_CASE);
strategy.setColumnNaming(NamingStrategy.LOWER_UNDERLINE);
mpg.setStrategy(strategy);
mpg.execute(); // 执行代码生成操作
}
}
```
此部分展示了如何通过 Java 编程方式调用 MyBatisPlus 提供的 API 来自动化地生成实体类、Mapper 接口以及其他组件文件[^2]。
#### 将生成的数据映射到前端图表展示-ECharts
假设已经成功利用上述方法生成了一个名为 `EchartsEntity` 和对应的 Mapper 文件,则可以在 Service 层编写逻辑处理函数用于获取数据,并将其转换成适合传递给 ECharts 图形库使用的 JSON 格式:
```java
@Service
@Slf4j
public class ChartService {
private final EchartsMapper echartsMapper;
@Autowired
public ChartService(EchartsMapper echartsMapper){
this.echartsMapper = echartsMapper;
}
/**
* 获取柱状图所需的数据集.
*/
public List<Map<String, Object>> getBarChartData(){
List<Echarts> list = echartsMapper.selectList(new QueryWrapper<>());
return list.stream().map(item -> Maps.newHashMap(
Map.entry("name", item.getName()),
Map.entry("value", item.getValue())
)).collect(Collectors.toList());
}
}
```
接着,在 Controller 中暴露 RESTful API 给前端请求访问这些经过加工后的统计数据:
```java
@RestController
@RequestMapping("/api/chart")
@RequiredArgsConstructor(onConstructor_=@Autowired)
public class ChartController {
private final ChartService chartService;
@GetMapping("/barData")
ResponseEntity<List<Map<String,Object>>> fetchBarChartDatas() throws Exception{
try {
var data = chartService.getBarChartData();
return ResponseEntity.ok(data);
} catch (Exception e) {
log.error(e.getMessage(),e);
throw new RuntimeException("Failed to load bar chart datas.");
}
}
}
```
最后一步是在前端页面引入 ECharts 库并通过 AJAX 请求从后端拉取最新统计信息绘制图形。这里给出一段简单的 HTML+JavaScript 实现作为例子:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<title>ECharts Example</title>
<script src="https://cdn.jsdelivr.net/npm/echarts/dist/echarts.min.js"></script>
<style type="text/css">
#main{width:600px;height:400px;}
</style>
</head>
<body>
<div id="main"></div>
<script type="text/javascript">
fetch('/api/chart/barData')
.then(response => response.json())
.then(function(result){
let myChart = echarts.init(document.getElementById('main'));
option = {
xAxis: {
type: 'category',
data: result.map(x=>x.name),
},
yAxis: {},
series: [{
name:'Value',
type:'bar',
data:result.map(x=>x.value),
}]
};
myChart.setOption(option);
});
</script>
</body>
</html>
```
这段脚本首先加载了远程服务器上的 `/api/chart/barData` 路径返回的结果集合,之后初始化一个新的 ECharts 对象实例并将之前获得的数据填充进去完成渲染过程[^1][^3].
阅读全文
相关推荐











