前言:
做一个微服务的商品模块。会用到的技术:springboot、springcloud、mybatisPlus、mybatisPlus的代码生成器(根据template模板生成)…
一、项目准备
(1)准备数据库表
会用到的三张表:商品分类=>商品品牌=>商品
(2)三张数据库表分析
(3)在公共基础子模块aigou_basic_parent中的aigou_basic_util工具模块中拷贝工具类进去
(4)创建商品项目结构
先创建项目的商品子模块父工程aigou_product_parent,然后再在aigou_product_parent中创建一个公共接口模块aigou_product_interface和服务模块aigou_product_service
(5)模块与模块之间引入依赖,进行关联
在商品的服务service模块的pom.xml中引入接口interface模块的依赖,然后接口interface模块的pom.xml中又要引用公共基础模块中的aigou_basic_util工具模块的依赖
(6)使用mybatisPlus代码生成
在这篇mybatisPlus入门学习 的博客中已经用过代码生成。所以这次就直接在原项目mp_parent中使用代码生成。在资源文件resources中改动代码生成后的路径、数据库的一些配置,以及修改config包中的配置文件中的表名、生成的目录路径等等配置。
1)、要生成controller层和query层代码,就需要template模板
在原项目mp_parent的资源文件中准备controller和query的template模板,用来生成两层的代码
- controller的模板。(CRUD操作的模板)
package ${package.Controller};
import ${package.Service}.${table.serviceName};
import ${package.Entity}.${entity};
import cn.lyq.aigou.util.AjaxResult;
import cn.lyq.aigou.util.PageList;
import com.baomidou.mybatisplus.plugins.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/${table.entityPath}")
public class ${entity}Controller {
@Autowired
public ${table.serviceName} ${table.entityPath}Service;
/**
* 保存和修改公用的
* @param ${table.entityPath} 传递的实体
* @return Ajaxresult转换结果
*/
@RequestMapping(value="/add",method= RequestMethod.POST)
public AjaxResult save(@RequestBody ${entity} ${table.entityPath}){
try {
if(${table.entityPath}.getId()!=null){
${table.entityPath}Service.updateById(${table.entityPath});
}else{
${table.entityPath}Service.insert(${table.entityPath});
}
return AjaxResult.me();
} catch (Exception e) {
e.printStackTrace();
return AjaxResult.me().setMsg("保存对象失败!"+e.getMessage());
}
}
/**
* 删除对象信息
* @param id
* @return
*/
@RequestMapping(value="/delete/{id}",method=RequestMethod.DELETE)
public AjaxResult delete(@PathVariable("id") Long id){
try {
${table.entityPath}Service.deleteById(id);
return AjaxResult.me();
} catch (Exception e) {
e.printStackTrace();
return AjaxResult.me().setMsg("删除对象失败!"+e.getMessage());
}
}
//获取用户
@RequestMapping(value = "/{id}",method = RequestMethod.GET)
public ${entity} get(@RequestParam(value="id",required=true) Long id)
{
return ${table.entityPath}Service.selectById(id);
}
/**
* 查看所有的员工信息
* @return
*/
@RequestMapping(value = "/list",method = RequestMethod.GET)
public List<${entity}> list(){
return ${table.entityPath}Service.selectList(null);
}
/**
* 分页查询数据
*
* @param query 查询对象
* @return PageList 分页对象
*/
@RequestMapping(value = "/json",method = RequestMethod.POST)
public PageList<${entity}> json(@RequestBody ${entity}Query query)
{
Page<${entity}> page = new Page<${entity}>(query.getPage(),query.getRows());
page = ${table.entityPath}Service.selectPage(page);
return new PageList<${entity}>(page.getTotal(),page.getRecords());
}
}
- query的模板
package cn.lyq.aigou.product.query;
import cn.lyq.aigou.util.BaseQuery;
/**
*
* @author ${author}
* @since ${date}
*/
public class ${table.entityName}Query extends BaseQuery{
}
2)、在商品子模块aigou_product_service服务模块的pom.xml中引入依赖
<dependencies>
<!--引入对interface接口模块的依赖-->
<dependency>
<groupId>cn.lyq</groupId>
<artifactId>aigou_product_interface</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<!--web/test-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<!--mysql数据库-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!--配置中心支持-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<!-- 注册中心Eureka 客户端依赖 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<!--swagger依赖-->
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
</dependencies>
3)、在商品子模块aigou_product_interface接口模块的pom.xml中引入依赖
mybatisPlus的依赖
<dependencies>
<!--引用公共基础模块中的aigou_basic_util工具模块的依赖-->
<dependency>
<groupId>cn.lyq</groupId>
<artifactId>aigou_basic_util</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<!--引入mybatisPlus的依赖-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
</dependencies>
4)、原项目mp_parent中修改的resources资源文件中的代码生成配置文件mpconofig.properties为
#此处为本项目src所在路径(代码生成器输出路径),注意一定是当前项目所在的目录哟
OutputDir=H:\\IDEA\\idea_workspace\\aigou_parent\\aigou_product_parent\\aigou_product_service\\src\\main\\java
#mapper.xml SQL映射文件目录
OutputDirXml=H:\\IDEA\\idea_workspace\\aigou_parent\\aigou_product_parent\\aigou_product_service\\src\\main\\resources
#我们生产代码要放的项目的地址:
OutputDirBase=H:\\IDEA\\idea_workspace\\aigou_parent\\aigou_product_parent\\aigou_product_service\\src\\main\\java
#我们生产代码要放的项目的地址:(可用作query层的生成目录)
OutputDirInterface=H:\\IDEA\\idea_workspace\\aigou_parent\\aigou_product_parent\\aigou_product_interface\\src\\main\\java
#设置作者
author=lyqtest
#自定义包路径,自动生成的包名
parent=cn.lyq.aigou.product
#数据库连接信息
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///aigou
jdbc.user=root
jdbc.pwd=123456
5)、在config包中修改的代码生成配置类GenteratorCode.java
以后可以直接拷贝过去修改即可使用
package cn.lyq.aigou.mp;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DbType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import java.util.*;
public class GenteratorCode {
public static void main(String[] args) throws InterruptedException {
//用来获取Mybatis-Plus.properties文件的配置信息
final ResourceBundle rb = ResourceBundle.getBundle("mpconfig");
AutoGenerator mpg = new AutoGenerator();
// 全局配置
GlobalConfig gc = new GlobalConfig();
gc.setOutputDir(rb.getString("OutputDir"));
//覆盖
gc.setFileOverride(true);
gc.setActiveRecord(true);// 开启 activeRecord 模式
gc.setEnableCache(false);// XML 二级缓存
gc.setBaseResultMap(true);// XML ResultMap
gc.setBaseColumnList(false);// XML columList
gc.setAuthor(rb.getString("author"));
//生成代码运行后不弹出生成的文件路径盘符
gc.setOpen(false);
mpg.setGlobalConfig(gc);
// 数据源配置
DataSourceConfig dsc = new DataSourceConfig();
//设置你数据库类型:
dsc.setDbType(DbType.MYSQL);
dsc.setTypeConvert(new MySqlTypeConvert());
dsc.setDriverName(rb.getString("jdbc.driver"));
dsc.setUsername(rb.getString("jdbc.user"));
dsc.setPassword(rb.getString("jdbc.pwd"));
dsc.setUrl(rb.getString("jdbc.url"));
mpg.setDataSource(dsc);
// 策略配置
StrategyConfig strategy = new StrategyConfig();
strategy.setTablePrefix(new String[] { "t_" });// 此处可以修改为您的表前缀
strategy.setNaming(NamingStrategy.underline_to_camel);// 表名生成策略
strategy.setInclude(new String[]{"t_brand"}); // 需要生成的表
mpg.setStrategy(strategy);
// 包配置
PackageConfig pc = new PackageConfig();
// parent:cn.itsource.aigou.mp
pc.setParent(rb.getString("parent"));
pc.setController("controller");
pc.setService("service");
pc.setServiceImpl("service.impl");
pc.setEntity("domain");
pc.setMapper("mapper");
mpg.setPackageInfo(pc);
// 注入自定义配置,可以在 VM 中使用 cfg.abc 【可无】
InjectionConfig cfg = new InjectionConfig() {
@Override
public void initMap() {
Map<String, Object> map = new HashMap<String, Object>();
map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-rb");
this.setMap(map);
}
};
List<FileOutConfig> focList = new ArrayList<FileOutConfig>();
// 调整 domain 生成目录演示
focList.add(new FileOutConfig("/templates/entity.java.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
return rb.getString("OutputDirInterface")+ "/cn/lyq/aigou/product/domain/" + tableInfo.getEntityName() + ".java";
}
});
// 调整 xml 生成目录演示:本来mybatis的mapper.xml应该放到resources下:路径应该和Mapper.java的路径一致:
focList.add(new FileOutConfig("/templates/mapper.xml.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
return rb.getString("OutputDirXml")+ "/cn/lyq/aigou/product/mapper/" + tableInfo.getEntityName() + "Mapper.xml";
}
});
// 调整 controller 生成目录演示
focList.add(new FileOutConfig("/templates/controller.java.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
return rb.getString("OutputDirBase")+ "/cn/lyq/aigou/product/controller/" + tableInfo.getEntityName() + "Controller.java";
}
});
// 调整 query 生成目录演示
focList.add(new FileOutConfig("/templates/query.java.vm") {
@Override
public String outputFile(TableInfo tableInfo) {
return rb.getString("OutputDirInterface")+ "/cn/lyq/aigou/product/query/" + tableInfo.getEntityName() + "Query.java";
}
});
cfg.setFileOutConfigList(focList);
mpg.setCfg(cfg);
// 自定义模板配置,可以 copy 源码 mybatis-plus/src/main/resources/templates 下面内容修改,
// 放置自己项目的 src/main/resources/templates 目录下, 默认名称一下可以不配置,也可以自定义模板名称
TemplateConfig tc = new TemplateConfig();
tc.setService("/templates/service.java.vm");
tc.setServiceImpl("/templates/serviceImpl.java.vm");
tc.setEntity(null);
tc.setMapper("/templates/mapper.java.vm");
tc.setController(null);
tc.setXml(null);
// 如上任何一个模块如果设置 空 OR Null 将不生成该模块。
mpg.setTemplate(tc);
// 执行生成
mpg.execute();
}
}
6)、最后在aigou_parent项目中生成的代码结构图示
- 接口interface子模块
- service服务子模块
(7)网关&swagger&注册中心客户端等的配置
对上面根据商品品牌表t_brand生成的service服务子模块的代码进行zuul网关、swagger接口和eureka注册中心客户端等配置。
1)、先在aigou_product_service模块中创建个启动类
@SpringBootApplication
@EnableEurekaClient// eureka的客户端
@MapperScan(basePackages="cn.lyq.aigou.product.mapper") //mapper和xml都扫描了
public class ProductApplication8002 {
public static void main(String[] args) {
SpringApplication.run(ProductApplication8002.class);
}
}
2)、在aigou_product_service模块中创建个config配置包,放入swagger的配置类
@Configuration
@EnableSwagger2
public class Swagger2 {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("cn.lyq.aigou.product.controller"))
//包:就是自己接口的包路径
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("商品系统api")//名字
.description("商品系统接口文档说明")//额外藐视
.contact(new Contact("wbtest", "", "liaoyongqiang@lyq.cn"))
.version("1.0")// 版本
.build();
}
}
3)、在aigou_product_service模块中进行YMAL配置application.yml文件(没有放入配置中心的时候)
server:
port: 8002
spring:
application:
name: AIGOU-PRODUCT
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql:///aigou
username: root
password: 123456
eureka:
client:
service-url:
defaultZone: http://localhost:7001/eureka
mybatis-plus:
type-aliases-package: cn.lyq.aigou.product.domain,cn.lyq.aigou.product.query #配置mapper映射中的别名
4)、在网关模块aigou_zuul_server_9527的YAML配置中进行商品服务的配置
5)、使用swagger接口管理
之前第2)步已经创建了swagger的配置类,并在pom.xml中引入了swagger的依赖
6)、测试
启动注册中心7001、再启动商品服务8002、启动网关9527、
- 都启动好之后,在浏览器地址栏输入地址:http://localhost:9527/swagger-ui.html 查看一下
二、CRUD操作
在上面的操作中,已经将controller类中的接口交给了swagger管理,所以接下来进行增删改查操作
1、根据id查询一条数据
2、增加一条数据
3、更新一条数据
由于在controller层的template模板中,添加方法add中已经做了id判断,有id就是修改操作,没有id就是增加操作。
4、删除操作
三、分页查询功能
1、分页功能实现
(1)、在aigou_product_service模块的config包中创建mybatisPlus的分页插件类
//Spring boot方式
@EnableTransactionManagement
@Configuration
@MapperScan("cn.lyq.aigou.product.mapper")
public class MybatisPlusConfig {
/**
* 分页插件
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
}
(2)、工具类模块aigou_basic_util中在上面拷贝插件类的时候已经将分页需要的数据类PageList拷好了。
//分页对象:easyui只需两个属性,total(总数),datas(分页数据)就能实现分页
public class PageList<T> {
private long total;
private List<T> rows = new ArrayList<>();
public long getTotal() {
return total;
}
public void setTotal(long total) {
this.total = total;
}
public List<T> getRows() {
return rows;
}
public void setRows(List<T> rows) {
this.rows = rows;
}
@Override
public String toString() {
return "PageList{" +
"total=" + total +
", rows=" + rows +
'}';
}
//提供有参构造方法,方便测试
public PageList(long total, List<T> rows) {
this.total = total;
this.rows = rows;
}
//除了有参构造方法,还需要提供一个无参构造方法
public PageList() {
}
}
(3)、query的父类BaseQuery中有查询的关键字KeyWord以及分页的当前页和每页条数的参数
public class BaseQuery {
//query做为查询: keyword
private String keyword;//查询关键字
private Integer page=1;//当前页 currentPage
private Integer rows=10;//每页条数 pageSize
public String getKeyword() {
return keyword;
}
public void setKeyword(String keyword) {
this.keyword = keyword;
}
public Integer getPage() {
return page;
}
public void setPage(Integer page) {
this.page = page;
}
public Integer getRows() {
return rows;
}
public void setRows(Integer rows) {
this.rows = rows;
}
}
(4)、通过代码生成器生成的aigou_product_service模块的BrandController类中的分页方法
/**
* 分页查询数据:
* 前台输入查询条件:
* 封装到query对象:
* 关键字条件:
* 分页对象的条件:
* @param query 查询对象
* @return PageList 分页对象
*/
@RequestMapping(value = "/json",method = RequestMethod.POST)
public PageList<Brand> json(@RequestBody BrandQuery query){
//page对象是baomidou包中的
Page<Brand> page = new Page<Brand>(query.getPage(),query.getRows());
//mybatisPlus的selectPage方法需要一个page对象参数
page = brandService.selectPage(page);
//返回给前台分页数据对象PageList。而参数page.getTotal()总条数和page.getRecords()数据方法都是baomidou包中的
return new PageList<Brand>(page.getTotal(),page.getRecords());
}
(5)、在swagger中测试
(6)、遇到的问题:在上面的分页查询中关键字KeyWord没起作用,接下来完善。
2、完善分页查询中关键字KeyWord
(1)、使用代码生成器生成商品分类productType的代码
(2)、分析商品品牌Brand类和商品分类ProductType类
两者表关系是一(商品分类)对多(商品品牌)关系,多表查询就要配置。此处就要在商品品牌Brand实体类中增加一个商品分类ProductType的对象字段
/**
* <p>
* 品牌信息
* </p>
* @author lyqtest
* @since 2019-05-10
* 通过mybatisPlus的注解@TableName给xml映射文件表明查这个表,通过 @TableField表名实体类和表中的字段不一致
*/
@TableName("t_brand")//mybatisPlus的注解,类上面打上表名的注解
public class Brand extends Model<Brand> {
private static final long serialVersionUID = 1L;
@TableId(value = "id", type = IdType.AUTO)
private Long id;
private Long createTime;
private Long updateTime;
/**
* 商品分类ID
*/
@TableField("product_type_id")//标识表中的字段是这样的,解决字段不一致
private Long productTypeId;
//商品品牌brand和商品分类productType是多对一关系。
@TableField(exist = false)//告诉数据库表t_brand中不存在这个字段。数据库操作就忽略它
private ProductType productType;
/**
* 用户姓名
*/
private String name;
/**
* 英文名
*/
private String englishName;
/**
* 首字母
*/
private String firstLetter;
private String description;
private Integer sortIndex;
/**
* 品牌LOGO
*/
private String logo;
public ProductType getProductType() {
return productType;
}
public void setProductType(ProductType productType) {
this.productType = productType;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getCreateTime() {
return createTime;
}
public void setCreateTime(Long createTime) {
this.createTime = createTime;
}
public Long getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Long updateTime) {
this.updateTime = updateTime;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEnglishName() {
return englishName;
}
public void setEnglishName(String englishName) {
this.englishName = englishName;
}
public String getFirstLetter() {
return firstLetter;
}
public void setFirstLetter(String firstLetter) {
this.firstLetter = firstLetter;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Long getProductTypeId() {
return productTypeId;
}
public void setProductTypeId(Long productTypeId) {
this.productTypeId = productTypeId;
}
public Integer getSortIndex() {
return sortIndex;
}
public void setSortIndex(Integer sortIndex) {
this.sortIndex = sortIndex;
}
public String getLogo() {
return logo;
}
public void setLogo(String logo) {
this.logo = logo;
}
@Override
protected Serializable pkVal() {
return this.id;
}
@Override
public String toString() {
return "Brand{" +
"id=" + id +
", createTime=" + createTime +
", updateTime=" + updateTime +
", productTypeId=" + productTypeId +
", productType=" + productType +
", name='" + name + '\'' +
", englishName='" + englishName + '\'' +
", firstLetter='" + firstLetter + '\'' +
", description='" + description + '\'' +
", sortIndex=" + sortIndex +
", logo='" + logo + '\'' +
'}';
}
}
- 重要部分代码图示:
(3)、分析PageList对象
该对象是返回给前台接收的对象。此对象需要两个参数total和rows,因此需要两条sql,一条查询条数,一条查询数据
(4)、在BrandMapper.xml映射文件中写相应的SQL语句。
注意:Brand中还有productType的关联属性,所以要进行手动映射。是对象就用,集合则用。此处是商品分类对象
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.lyq.aigou.product.mapper.BrandMapper">
<!-- 通用查询映射结果 -->
<resultMap id="BaseResultMap" type="cn.lyq.aigou.product.domain.Brand">
<id column="id" property="id" />
<result column="createTime" property="createTime" />
<result column="updateTime" property="updateTime" />
<result column="name" property="name" />
<result column="englishName" property="englishName" />
<result column="firstLetter" property="firstLetter" />
<result column="description" property="description" />
<result column="product_type_id" property="productTypeId" />
<result column="sortIndex" property="sortIndex" />
<result column="logo" property="logo" />
</resultMap>
<resultMap id="BrandMap" type="cn.lyq.aigou.product.domain.Brand">
<!--自己的属性-->
<!--先封装主键
column="" ==》数据库的列
property="" ==》domain的属性
-->
<id column="id" property="id" />
<!--再封装非主键-->
<result column="createTime" property="createTime" />
<result column="updateTime" property="updateTime" />
<result column="name" property="name" />
<result column="englishName" property="englishName" />
<result column="firstLetter" property="firstLetter" />
<result column="description" property="description" />
<result column="product_type_id" property="productTypeId" />
<result column="sortIndex" property="sortIndex" />
<result column="logo" property="logo" />
<!--手动映射关联属性
private ProductType productType;
-->
<association property="productType" javaType="ProductType">
<id column="pid" property="id" />
<result column="pname" property="name" />
</association>
</resultMap>
<!--long queryPageCount(BrandQuery brandQuery);-->
<select id="queryPageCount" resultType="long" parameterType="BrandQuery">
SELECT
count(*)
FROM
t_brand b
LEFT JOIN t_product_type pt ON b.product_type_id = pt.id
<include refid="whereSql"/>
</select>
<!-- List<Brand> queryPageList(BrandQuery brandQuery);-->
<select id="queryPageList" resultMap="BrandMap" parameterType="BrandQuery">
SELECT
b.id,
b.createTime,
b.updateTime,
b.name,
b.englishName,
b.firstLetter,
b.description,
b.product_type_id,
b.sortIndex,
b.logo,
pt.id pid,
pt.name pname
FROM
t_brand b
LEFT JOIN t_product_type pt ON b.product_type_id = pt.id
<include refid="whereSql"/>
limit #{start},#{rows}
</select>
<!--where b.name like '%D%' or b.englishName like '%D%'-->
<sql id="whereSql">
<where>
<if test="keyword!=null and keyword!=''">
b.name like CONCAT('%',#{keyword},'%') or b.englishName like CONCAT('%',#{keyword},'%')
</if>
</where>
</sql>
</mapper>
- 重要部分图示:
(5)、BaseQuery中的针对xml映射文件中分页的开始索引配置
(6)、在BrandMapper.java中写对应xml映射文件中的sql语句方法
(7)、在service层写相应的接口和实现
- service接口:IBrandService
- service的实现类:BrandServiceImpl
调用了mapper层中的两个方法来满足service层的这一个方法
(8)、controller层
(9)、测试完成高级查询+分页
四、商品品牌前台页面展示
1、展示数据
<template>
<section>
<!--工具条-->
<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
<el-form :inline="true" :model="filters">
<el-form-item>
<el-input v-model="filters.name" placeholder="姓噼噼啪啪铺铺铺铺铺铺铺铺铺铺铺名"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" v-on:click="getBrands">查询</el-button>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="handleAdd">新增</el-button>
</el-form-item>
</el-form>
</el-col>
<!--列表-->
<el-table :data="brands" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
<el-table-column type="selection" width="55">
</el-table-column>
<el-table-column type="index" width="60">
</el-table-column>
<el-table-column prop="name" label="名称" width="120" sortable>
</el-table-column>
<el-table-column prop="sex" label="性别" width="100" :formatter="formatSex" sortable>
</el-table-column>
<el-table-column prop="age" label="年龄" width="100" sortable>
</el-table-column>
<el-table-column prop="birth" label="生日" width="120" sortable>
</el-table-column>
<el-table-column prop="addr" label="地址" min-width="180" sortable>
</el-table-column>
<el-table-column label="操作" width="150">
<template scope="scope">
<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
</template>
</el-table-column>
</el-table>
<!--工具条-->
<el-col :span="24" class="toolbar">
<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="20" :total="total" style="float:right;">
</el-pagination>
</el-col>
<!--编辑界面-->
<el-dialog title="编辑" v-model="editFormVisible" :close-on-click-modal="false">
<el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
<el-form-item label="姓名" prop="name">
<el-input v-model="editForm.name" auto-complete="off"></el-input>
</el-form-item>
<el-form-item label="性别">
<el-radio-group v-model="editForm.sex">
<el-radio class="radio" :label="1">男</el-radio>
<el-radio class="radio" :label="0">女</el-radio>
</el-radio-group>
</el-form-item>
<el-form-item label="年龄">
<el-input-number v-model="editForm.age" :min="0" :max="200"></el-input-number>
</el-form-item>
<el-form-item label="生日">
<el-date-picker type="date" placeholder="选择日期" v-model="editForm.birth"></el-date-picker>
</el-form-item>
<el-form-item label="地址">
<el-input type="textarea" v-model="editForm.addr"></el-input>
</el-form-item>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button @click.native="editFormVisible = false">取消</el-button>
<el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
</div>
</el-dialog>
<!--新增界面-->
<el-dialog title="新增" v-model="addFormVisible" :close-on-click-modal="false">
<el-form :model="addForm" label-width="80px" :rules="addFormRules" ref="addForm">
<el-form-item label="姓名" prop="name">
<el-input v-model="addForm.name" auto-complete="off"></el-input>
</el-form-item>
<el-form-item label="性别">
<el-radio-group v-model="addForm.sex">
<el-radio class="radio" :label="1">男</el-radio>
<el-radio class="radio" :label="0">女</el-radio>
</el-radio-group>
</el-form-item>
<el-form-item label="年龄">
<el-input-number v-model="addForm.age" :min="0" :max="200"></el-input-number>
</el-form-item>
<el-form-item label="生日">
<el-date-picker type="date" placeholder="选择日期" v-model="addForm.birth"></el-date-picker>
</el-form-item>
<el-form-item label="地址">
<el-input type="textarea" v-model="addForm.addr"></el-input>
</el-form-item>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button @click.native="addFormVisible = false">取消</el-button>
<el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
</div>
</el-dialog>
</section>
</template>
<script>
import util from '../../common/js/util'
//import NProgress from 'nprogress'
import { getUserListPage, removeUser, batchRemoveUser, editUser, addUser } from '../../api/api';
export default {
data() {
return {
filters: {
name: ''
},
brands: [],
total: 0,
page: 1,
listLoading: false,
sels: [],//列表选中列
editFormVisible: false,//编辑界面是否显示
editLoading: false,
editFormRules: {
name: [
{ required: true, message: '请输入姓名', trigger: 'blur' }
]
},
//编辑界面数据
editForm: {
id: 0,
name: '',
sex: -1,
age: 0,
birth: '',
addr: ''
},
addFormVisible: false,//新增界面是否显示
addLoading: false,
addFormRules: {
name: [
{ required: true, message: '请输入姓名', trigger: 'blur' }
]
},
//新增界面数据
addForm: {
name: '',
sex: -1,
age: 0,
birth: '',
addr: ''
}
}
},
methods: {
//性别显示转换
formatSex: function (row, column) {
return row.sex == 1 ? '男' : row.sex == 0 ? '女' : '未知';
},
handleCurrentChange(val) {
this.page = val;
this.getBrands();
},
//获取用户列表
getBrands() {
let para = {
page: this.page,
name: this.filters.name
};
this.listLoading = true;
//NProgress.start();
//使用axios调用后台方法查询数据。路径要从网关9527中拿
this.$http.post("/product/brand/json",para).then((res) => {
this.total = res.data.total;
this.brands = res.data.rows;
this.listLoading = false;
});
},
//删除
handleDel: function (index, row) {
this.$confirm('确认删除该记录吗?', '提示', {
type: 'warning'
}).then(() => {
this.listLoading = true;
//NProgress.start();
let para = { id: row.id };
removeUser(para).then((res) => {
this.listLoading = false;
//NProgress.done();
this.$message({
message: '删除成功',
type: 'success'
});
this.getBrands();
});
}).catch(() => {
});
},
//显示编辑界面
handleEdit: function (index, row) {
this.editFormVisible = true;
this.editForm = Object.assign({}, row);
},
//显示新增界面
handleAdd: function () {
this.addFormVisible = true;
this.addForm = {
name: '',
sex: -1,
age: 0,
birth: '',
addr: ''
};
},
//编辑
editSubmit: function () {
this.$refs.editForm.validate((valid) => {
if (valid) {
this.$confirm('确认提交吗?', '提示', {}).then(() => {
this.editLoading = true;
//NProgress.start();
let para = Object.assign({}, this.editForm);
para.birth = (!para.birth || para.birth == '') ? '' : util.formatDate.format(new Date(para.birth), 'yyyy-MM-dd');
editUser(para).then((res) => {
this.editLoading = false;
//NProgress.done();
this.$message({
message: '提交成功',
type: 'success'
});
this.$refs['editForm'].resetFields();
this.editFormVisible = false;
this.getBrands();
});
});
}
});
},
//新增
addSubmit: function () {
this.$refs.addForm.validate((valid) => {
if (valid) {
this.$confirm('确认提交吗?', '提示', {}).then(() => {
this.addLoading = true;
//NProgress.start();
let para = Object.assign({}, this.addForm);
para.birth = (!para.birth || para.birth == '') ? '' : util.formatDate.format(new Date(para.birth), 'yyyy-MM-dd');
addUser(para).then((res) => {
this.addLoading = false;
//NProgress.done();
this.$message({
message: '提交成功',
type: 'success'
});
this.$refs['addForm'].resetFields();
this.addFormVisible = false;
this.getBrands();
});
});
}
});
},
selsChange: function (sels) {
this.sels = sels;
},
//批量删除
batchRemove: function () {
var ids = this.sels.map(item => item.id).toString();
this.$confirm('确认删除选中记录吗?', '提示', {
type: 'warning'
}).then(() => {
this.listLoading = true;
//NProgress.start();
let para = { ids: ids };
batchRemoveUser(para).then((res) => {
this.listLoading = false;
//NProgress.done();
this.$message({
message: '删除成功',
type: 'success'
});
this.getBrands();
});
}).catch(() => {
});
}
},
//加载完成后调用方法查询数据
mounted() {
this.getBrands();
}
}
</script>
<style scoped>
</style>
- 基于之前修改的代码图示
- 最后前台页面展示
2、商品品牌页面的CRUD操作
(1)、整体的商品品牌brand.vue的js代码
<template>
<section>
<!--工具条-->
<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
<el-form :inline="true" :model="filters">
<el-form-item>
<el-input v-model="filters.keyword" placeholder="关键字"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" v-on:click="getBrands">查询</el-button>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="handleAdd">新增</el-button>
</el-form-item>
</el-form>
</el-col>
<!--列表-->
<el-table :data="brands" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
<el-table-column type="selection" width="55">
</el-table-column>
<el-table-column type="index" width="60">
</el-table-column>
<el-table-column prop="name" label="姓名" width="180" sortable>
</el-table-column>
<el-table-column prop="englishName" label="英文名" width="200" sortable>
</el-table-column>
<!--有点屌-->
<el-table-column prop="productType.name" label="商品类型" width="180" sortable>
</el-table-column>
<el-table-column prop="description" label="描述" min-width="250" sortable>
</el-table-column>
<el-table-column label="操作" width="150">
<template scope="scope">
<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
</template>
</el-table-column>
</el-table>
<!--工具条-->
<el-col :span="24" class="toolbar">
<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="10" :total="total" style="float:right;">
</el-pagination>
</el-col>
<!--编辑界面-->
<el-dialog title="编辑" v-model="formVisible" :close-on-click-modal="false">
<el-form :model="form" label-width="80px" :rules="formRules" ref="form">
<el-form-item label="名称" prop="name">
<el-input v-model="form.name" auto-complete="off"></el-input>
</el-form-item>
<el-form-item label="英文名" prop="englishName">
<el-input v-model="form.englishName" auto-complete="off"></el-input>
</el-form-item>
<el-form-item label="logo" prop="logo">
<el-upload
class="upload-demo"
action="http://127.0.0.1:9527/services/common/upload"
:on-preview="handlePreview"
:on-remove="handleRemove"
:file-list="fileList2"
:on-success="handleSuccess"
list-type="picture"
>
<el-button size="small" type="primary">点击上传</el-button>
<div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
</el-upload>
</el-form-item>
<el-form-item label="排序号" prop="sortIndex">
<el-input v-model="form.sortIndex" auto-complete="off"></el-input>
</el-form-item>
<el-form-item label="类型" prop="productTypeId">
<el-input v-model="form.productTypeId" auto-complete="off"></el-input>
</el-form-item>
<el-form-item label="描述" prop="description">
<el-input v-model="form.description" auto-complete="off"></el-input>
</el-form-item>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button @click.native="formVisible = false">取消</el-button>
<el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
</div>
</el-dialog>
</section>
</template>
<script>
export default {
data() { //数据
return {
filters: {
keyword: ''
},
brands: [],
total: 0,
page: 1,
listLoading: false,
sels: [],//列表选中列
fileList2: [],
formVisible: false,//编辑界面是否显示
editLoading: false,
formRules: {
name: [
{ required: true, message: '请输入姓名', trigger: 'blur' }
]
},
//编辑界面数据
form: {
id: 0,
name: '',
englishName: '',
sortIndex: '',
description: '',
logo: '',
productTypeId: 0
}
}
},
methods: { //方法\
handleSuccess(response, file, fileList){
//上传成功回调
this.form.logo = file.response.resultObj;
},
handleRemove(file, fileList) {
var filePath =file.response.resultObj;
this.$http.delete("/common/del?filePath="+filePath)
.then(res=>{
if(res.data.success){
this.$message({
message: '删除成功!',
type: 'success'
});
}else{
this.$message({
message: '删除失败!',
type: 'error'
});
}
})
},
handlePreview(file) {
console.log(file);
},
handleCurrentChange(val) {
this.page = val;
this.getBrands();
},
//获取品牌的列表:
getBrands() {
//查询条件
let para = {
page: this.page,
keyword: this.filters.keyword
};
//加载
this.listLoading = true;
//异步请求:
this.$http.post("/product/brand/json",para)
.then((res) => {
console.log(res);
this.total = res.data.total;
this.brands = res.data.rows;
this.listLoading = false;
});
},
//删除
handleDel: function (index, row) {
this.$confirm('确认删除该记录吗?', '提示', {
type: 'warning'
}).then(() => {
this.listLoading = true;
//NProgress.start();
let id = row.id ;
this.$http.delete("/product/brand/delete/"+id)
.then((res) => {
let { msg, success, object } = res.data;
if (!success) {
this.$message({
message: msg,
type: 'error'
});
} else {
this.listLoading = false;
//NProgress.done();
this.$message({
message: '删除成功',
type: 'success'
});
this.getBrands();
}
});
}).catch(() => {
});
},
//显示编辑界面
handleEdit: function (index, row) {
this.formVisible = true;
//回显 要提交后台
this.form = Object.assign({}, row);
//回显缩略图
this.fileList2.push({
"url":this.$staticIp+row.logo
})
},
//显示新增界面
handleAdd: function () {
this.formVisible = true;
this.form = {
name: '',
englishName: '',
sortIndex: '',
description: '',
logo: '',
productTypeId: 0
};
},
//编辑
editSubmit: function () {
this.$refs.form.validate((valid) => {
if (valid) {
console.log(this.fileList2);
this.$confirm('确认提交吗?', '提示', {}).then(() => {
this.editLoading = true;
let para = Object.assign({}, this.form);
this.$http.post("/product/brand/add",para).then((res) => {
this.editLoading = false;
this.$message({
message: '提交成功',
type: 'success'
});
this.$refs['form'].resetFields();
this.formVisible = false;
this.getBrands();
});
});
}
});
},
selsChange: function (sels) {
this.sels = sels;
},
//批量删除
batchRemove: function () {
var ids = this.sels.map(item => item.id).toString();
this.$confirm('确认删除选中记录吗?', '提示', {
type: 'warning'
}).then(() => {
this.listLoading = true;
//NProgress.start();
let para = { ids: ids };
batchRemoveUser(para).then((res) => {
this.listLoading = false;
//NProgress.done();
this.$message({
message: '删除成功',
type: 'success'
});
this.getBrands();
});
}).catch(() => {
});
}
}, // $(function()) 加载完毕后执行
mounted() {
this.getBrands();
}
}
</script>
<style scoped>
</style>
(2)、高级查询+分页功能
(3)、增加数据
(4)、删除数据
(5)、修改数据
五、商品类型的树状结构展示
1、商品类型的数据库表展示
字段pid表示层级关系
2、elementUi的树状结构图
3、最终商品类型树状图要展示的效果
4、在商品类型类中增加一个children字段
5、controller层
6、实现树状结构的第一种方法:递归方式
(1)、service层准备接口方法
(2)、service层的实现类
树状结构重要的代码
@Service
public class ProductTypeServiceImpl extends ServiceImpl<ProductTypeMapper, ProductType> implements IProductTypeService {
//注入mapper对象
@Autowired
private ProductTypeMapper productTypeMapper;
//实现树状结构
@Override
public List<ProductType> treeData() {
//递归方法。查看商品类型数据库表得知pid=0为最上一级,返回前台的都是一级菜单
return treeDataRecursion(0L);
}
/**
* 递归:
* 自己方法里调用自己,但是必须有一个出口:没有儿子就出去;
* 好么:
* 不好,因为每次都要发送sql,就要发送很多的sql:
* 要耗时;数据库的服务器要承受很多的访问量,压力大。
* ====》原因是发送了很多sql,我优化就少发送,至少发送1条。
* @return
*/
public List<ProductType> treeDataRecursion(Long pid){
//拿到所有的一级菜单。调用下面的getAllChildren方法
List<ProductType> allChildren = getAllChildren(pid);
//设置一个出口:没有儿子就不用遍历,直接返回null
if(allChildren==null||allChildren.size()==0){
return null;
}
//否则,就要遍历找到当前对象的所有儿子
for (ProductType child : allChildren) {
//调用自己的方法,找到自己的儿子。
//看数据库表就能明白。根据自己的对象的id找自己的儿子
List<ProductType> productTypes = treeDataRecursion(child.getId());
//再将自己的儿子存放进来。productType实体类中的set方法
child.setChildren(productTypes);
}
//返回装好的菜单
return allChildren;
}
/**
* 查询数据的pid=pid的:
* // select * from t_product_type where pid = 2
* @param pid
* @return
*/
public List<ProductType> getAllChildren(Long pid){
//准备baomidou包的wrapper对象
Wrapper<ProductType> wrapper=new EntityWrapper<>();
//wrapper的eq方法:参数是数据库列名和数据值。查询数据库中列名为pid,并且传进来的参数为pid的数据
wrapper.eq("pid", pid);
//mybatisPlus的selectList方法需要一个wrapper对象
return productTypeMapper.selectList(wrapper);
}
}
- 画图解释一波上面的代码构成
7、再使用循环的方式实现商品分类的树状图
递归方式每次都要发送sql,数据库要接收很多的访问量,压力大。循环方式:发送一条sql语句,然后在内存中组装父子关系
(1)、service层接口方法
(2)、service层实现类
@Service
public class ProductTypeServiceImpl extends ServiceImpl<ProductTypeMapper, ProductType> implements IProductTypeService {
//注入mapper对象
@Autowired
private ProductTypeMapper productTypeMapper;
//实现树状结构
@Override
public List<ProductType> treeData() {
//循环方法。返回前台的都是一级菜单
return treeDataLoop();
}
/**
* 步骤:循环查询
* 1:先查询出所有的数据
* 2:再组装父子结构
* @return
*/
public List<ProductType> treeDataLoop() {
//返回的一级菜单
List<ProductType> result = new ArrayList<>();
//1.先查询出所有的数据。selectList方法的参数mapper为null即可
List<ProductType> productTypes = productTypeMapper.selectList(null);
//定义一个map集合。参数是id和productType类
Map<Long,ProductType> map=new HashMap<>();
//再循环查出来的对象,放到map集合中去
for (ProductType cur : productTypes) {
//将对象的id和对象放map集合中去
map.put(cur.getId(), cur);
}
//2.组装父子结构。遍历上面查询到的数据,拿到当前对象
for (ProductType current : productTypes) {
//找到一级菜单
if(current.getPid()==0){
//装到上面定义的result集合中去
result.add(current);
}else{
//否则就不是一级菜单,你是儿子。那么是哪个对象的儿子?
//先定义一个老子菜单
ProductType parent=null;
/*嵌套循环了,更加影响数据库性能,所以不用,用上面定义的map集合方式存放查询出来的数据
/再循环查出来的数据
for (ProductType cur : productTypes) {
//如果cur对象的id就是current对象的pid,那么cur对象就是老子。多找一下表中的id和pid的关系
if(cur.getId()==current.getPid()){
//cur对象就是老子
parent=cur;
}
}
*/
//和上面嵌套循环一个意思。如果map集合中的cur对象的id就是current对象的pid,那么cur对象就是老子。多找一下表中的id和pid的关系
parent = map.get(current.getPid());
//然后拿到老子的儿子
List<ProductType> children = parent.getChildren();
//然后将你自己加进去。你自己是你老子的儿子
children.add(current);
}
}
//返回装好的一级菜单
return result;
}
}
- 画图解释一波