介绍:
本篇我们介绍一下Springboot整合MyBatisPlus后台相对比较完整的代码,以swager来进行测试。
主要依赖
<!--mybatis-plus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.3.1</version>
</dependency>
<!--freemarker-->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.30</version>
</dependency>
<!--代码生成器-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.4.1</version>
</dependency>
<!--swagger-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
代码生成器代码
public class CodeGenerator {
/**
* <p>
* 读取控制台内容
* </p>
*/
public static String scanner(String tip) {
Scanner scanner = new Scanner(System.in);
StringBuilder help = new StringBuilder();
help.append("请输入" + tip + ":");
System.out.println(help.toString());
if (scanner.hasNext()) {
String ipt = scanner.next();
if (StringUtils.isNotBlank(ipt)) {
return ipt;
}
}
throw new MybatisPlusException("请输入正确的" + tip + "!");
}
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("elite");
gc.setOpen(false);
// gc.setSwagger2(true); 实体属性 Swagger2 注解
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
dsc.setUrl("jdbc:mysql://数据库ip:3306/test?useUnicode=true&useSSL=false&characterEncoding=utf8");
// dsc.setSchemaName("public");
dsc.setDriverName("com.mysql.jdbc.Driver");
dsc.setUsername("root");
dsc.setPassword("123456");
mpg.setDataSource(dsc);
// 包配置
PackageConfig pc = new PackageConfig();
pc.setModuleName(scanner("模块名"));
pc.setParent("com.elite");
mpg.setPackageInfo(pc);
// 自定义配置
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
// to do nothing
}
};
// 如果模板引擎是 freemarker
String templatePath = "/templates/mapper.xml.ftl";
// 如果模板引擎是 velocity
// String templatePath = "/templates/mapper.xml.vm";
// 自定义输出配置
List<FileOutConfig> focList = new ArrayList<>();
// 自定义配置会被优先输出
focList.add(new FileOutConfig(templatePath) {
@Override
public String outputFile(TableInfo tableInfo) {
// 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
return projectPath + "/src/main/resources/mapper/" + pc.getModuleName()
+ "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
}
});
/*
cfg.setFileCreate(new IFileCreate() {
@Override
public boolean isCreate(ConfigBuilder configBuilder, FileType fileType, String filePath) {
// 判断自定义文件夹是否需要创建
checkDir("调用默认方法创建的目录,自定义目录用");
if (fileType == FileType.MAPPER) {
// 已经生成 mapper 文件判断存在,不想重新生成返回 false
return !new File(filePath).exists();
}
// 允许生成模板文件
return true;
}
});
*/
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
// 配置模板
TemplateConfig templateConfig = new TemplateConfig();
// 配置自定义输出模板
//指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
// templateConfig.setEntity("templates/entity2.java");
// templateConfig.setService();
// templateConfig.setController();
templateConfig.setXml(null);
mpg.setTemplate(templateConfig);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
//strategy.setSuperEntityClass("BaseEntity");
strategy.setEntityLombokModel(true);
strategy.setRestControllerStyle(true);
// 公共父类
//strategy.setSuperControllerClass("你自己的父类控制器,没有就不用设置!");
// 写于父类中的公共字段
//strategy.setSuperEntityColumns("id");
//strategy.setSuperEntityColumns("id");
//strategy.setSuperEntityColumns("id");
//strategy.setSuperEntityColumns("id");
strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
strategy.setControllerMappingHyphenStyle(true);
strategy.setTablePrefix(pc.getModuleName() + "_");
mpg.setStrategy(strategy);
mpg.setTemplateEngine(new FreemarkerTemplateEngine());
mpg.execute();
}
}
执行代码生成器,系统会自动生成controller,service以及mapper。mybatisplus提供了部分封装好的方法。
service层
/**
* <p>
* 订单表 服务类
* </p>
*
* @author elite
* @since 2022-08-22
*/
public interface IOrderService extends IService<Order> {
}
/**
* <p>
* 订单表 服务实现类
* </p>
*
* @author elite
* @since 2022-08-22
*/
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {
}
mapper
/**
* <p>
* 订单表 Mapper 接口
* </p>
*
* @author elite
* @since 2022-08-22
*/
public interface OrderMapper extends BaseMapper<Order> {
}
controller
/**
* <p>
* 订单表 前端控制器
* </p>
*
* @author elite
* @since 2022-08-22
*/
@RestController
@RequestMapping("/springboot/order")
@Api(tags = "订单接口")
public class OrderController {
@Autowired
IOrderService orderService;
/**
* 获取订单列表
*/
@ApiOperation(value = "获取订单列表")
@GetMapping("/getOrderList")
public R getOrderList(){
List<Order> orderList = orderService.list();
return R.ok(orderList);
}
/**
* 分页获取订单列表
*/
@ApiOperation(value = "分页获取订单列表")
@PostMapping("/getOrderListByPage/{currentPage}/{PageSize}")
public R getOrderListPage(@PathVariable("currentPage")Integer currentPage,
@PathVariable("PageSize") Integer PageSize,
@RequestBody Order order){
QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
IPage<Order> page = new Page<>();
page.setCurrent(currentPage);
page.setSize(PageSize);
//订单ID
//queryWrapper.eq("order_id",order.getOrderId());
queryWrapper.eq("order_no",order.getOrderNo());
IPage<Order> Orders = orderService.page(page, queryWrapper);
return R.ok(Orders);
}
/**
* 通过订单ID获取订单信息
*/
@ApiOperation(value = "通过订单ID获取订单信息")
@GetMapping("/getOrderById/{order_id}")
public R getOrderById(@PathVariable("order_id") Integer order_id){
Order order = orderService.getById(order_id);
return R.ok(order);
}
/**
* 保存订单信息
*/
@ApiOperation(value = "保存订单信息")
@PostMapping("/saveOrder")
public R saveOrder(@RequestBody Order order){
boolean save = orderService.save(order);
if (save){
return R.ok(null);
}
return R.fail();
}
/**
* 更新订单信息
*/
@ApiOperation(value = "更新订单信息")
@PutMapping("/updateOrder")
public R updateOrder(@RequestBody Order order){
Wrapper<Order> updateWrapper = new UpdateWrapper<>();
boolean success = orderService.update(updateWrapper);
if (success){
return R.ok(null);
}
return R.fail();
}
/**
* 删除订单信息
*/
@ApiOperation(value = "删除订单信息")
@DeleteMapping("/delOrderById")
public R delOrderById(@PathVariable("order_id") Integer order_id){
boolean success = orderService.removeById(order_id);
if (success){
return R.ok(null);
}
return R.fail();
}
}
实体类Order
**
* <p>
* 订单表
* </p>
*
* @author elite
* @since 2022-08-22
*/
@ApiModel("订单表")
@Data
@EqualsAndHashCode(callSuper = false)
@TableName("`order`")
public class Order implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 订单ID
*/
@ApiModelProperty(value = "订单ID")
@TableId(value = "order_id", type = IdType.AUTO)
private Integer orderId;
/**
* 订单号
*/
@TableField(value = "order_no")
private Integer orderNo;
/**
* 产品id
*/
@TableField(value = "product_id")
private Integer productId;
/**
* 用户ID
*/
@TableField(value = "user_id")
private Integer userId;
/**
* 订单产品数量
*/
@TableField(value = "order_num")
private Integer orderNum;
/**
* 订单金额
*/
@TableField(value = "order_amt")
private BigDecimal orderAmt;
/**
* 订单状态
*/
@TableField(value = "order_status")
private String orderStatus;
/**
* 支付状态
*/
@TableField(value = "pay_status")
private String payStatus;
/**
* 创建时间
*/
@TableField(value = "create_time")
private LocalDateTime createTime;
/**
* 更新时间
*/
@TableField(value = "update_time")
private LocalDateTime updateTime;
/**
* 创建人
*/
@TableField(value = "create_user")
private String createUser;
/**
* 更新人
*/
@TableField(value = "update_user")
private String updateUser;
}
swagger
API Developmentfor Everyone
Simplify API development for users, teams, and enterprises with the Swagger open source and professional toolset. Find out how Swagger can help you design and document your APIs at scale.
制作API接口文档非常方便
常用的注解:
@Api:标注在一个类上
@ApiOperation :在方法上
@ApiModel :用于标注一个实体类
@ApiModelProperty:标注属性
接口文档访问地址:
http://ip地址:port/swagger-ui.html#/
分页测试
Response body
Download
{
"code": 200,
"msg": "成功",
"data": {
"records": [
{
"orderId": 3,
"orderNo": 2,
"productId": 2,
"userId": 1,
"orderNum": 2,
"orderAmt": 20,
"orderStatus": "取消下单",
"payStatus": "未支付",
"createTime": "2022-08-21T11:20:29",
"updateTime": "2022-08-21T11:20:29",
"createUser": "annotation",
"updateUser": "annotation"
}
],
"total": 1,
"size": 2,
"current": 1,
"orders": [],
"optimizeCountSql": true,
"hitCount": false,
"countId": null,
"maxLimit": null,
"searchCount": true,
"pages": 1
}
}