做一个微服务的商品模块。会用到的技术:springboot、springcloud、mybatisPlus、mybatisPlus的代码生成器(根据template模板生成)…
先创建项目的商品子模块父工程aigou_product_parent,然后再在aigou_product_parent中创建一个公共接口模块aigou_product_interface和服务模块aigou_product_service
在商品的服务service模块的pom.xml中引入接口interface模块的依赖,然后接口interface模块的pom.xml中又要引用公共基础模块中的aigou_basic_util工具模块的依赖
在这篇mybatisPlus入门学习 的博客中已经用过代码生成。所以这次就直接在原项目mp_parent中使用代码生成。在资源文件resources中改动代码生成后的路径、数据库的一些配置,以及修改config包中的配置文件中的表名、生成的目录路径等等配置。
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());
}
}
package cn.lyq.aigou.product.query;
import cn.lyq.aigou.util.BaseQuery;
/**
*
* @author ${author}
* @since ${date}
*/
public class ${table.entityName}Query extends BaseQuery{
}
cn.lyq
aigou_product_interface
1.0-SNAPSHOT
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-test
mysql
mysql-connector-java
org.springframework.cloud
spring-cloud-starter-config
org.springframework.cloud
spring-cloud-starter-netflix-eureka-client
io.springfox
springfox-swagger2
2.9.2
io.springfox
springfox-swagger-ui
2.9.2
mybatisPlus的依赖
cn.lyq
aigou_basic_util
1.0-SNAPSHOT
com.baomidou
mybatis-plus-boot-starter
2.2.0
#此处为本项目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
以后可以直接拷贝过去修改即可使用
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 map = new HashMap();
map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-rb");
this.setMap(map);
}
};
List focList = new ArrayList();
// 调整 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();
}
}
对上面根据商品品牌表t_brand生成的service服务子模块的代码进行zuul网关、swagger接口和eureka注册中心客户端等配置。
@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);
}
}
@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", "", "[email protected]"))
.version("1.0")// 版本
.build();
}
}
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映射中的别名
之前第2)步已经创建了swagger的配置类,并在pom.xml中引入了swagger的依赖
启动注册中心7001、再启动商品服务8002、启动网关9527、
在上面的操作中,已经将controller类中的接口交给了swagger管理,所以接下来进行增删改查操作
由于在controller层的template模板中,添加方法add中已经做了id判断,有id就是修改操作,没有id就是增加操作。
//Spring boot方式
@EnableTransactionManagement
@Configuration
@MapperScan("cn.lyq.aigou.product.mapper")
public class MybatisPlusConfig {
/**
* 分页插件
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
}
//分页对象:easyui只需两个属性,total(总数),datas(分页数据)就能实现分页
public class PageList {
private long total;
private List rows = new ArrayList<>();
public long getTotal() {
return total;
}
public void setTotal(long total) {
this.total = total;
}
public List getRows() {
return rows;
}
public void setRows(List rows) {
this.rows = rows;
}
@Override
public String toString() {
return "PageList{" +
"total=" + total +
", rows=" + rows +
'}';
}
//提供有参构造方法,方便测试
public PageList(long total, List rows) {
this.total = total;
this.rows = rows;
}
//除了有参构造方法,还需要提供一个无参构造方法
public PageList() {
}
}
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;
}
}
/**
* 分页查询数据:
* 前台输入查询条件:
* 封装到query对象:
* 关键字条件:
* 分页对象的条件:
* @param query 查询对象
* @return PageList 分页对象
*/
@RequestMapping(value = "/json",method = RequestMethod.POST)
public PageList json(@RequestBody BrandQuery query){
//page对象是baomidou包中的
Page page = new Page(query.getPage(),query.getRows());
//mybatisPlus的selectPage方法需要一个page对象参数
page = brandService.selectPage(page);
//返回给前台分页数据对象PageList。而参数page.getTotal()总条数和page.getRecords()数据方法都是baomidou包中的
return new PageList(page.getTotal(),page.getRecords());
}
两者表关系是一(商品分类)对多(商品品牌)关系,多表查询就要配置。此处就要在商品品牌Brand实体类中增加一个商品分类ProductType的对象字段
/**
*
* 品牌信息
*
* @author lyqtest
* @since 2019-05-10
* 通过mybatisPlus的注解@TableName给xml映射文件表明查这个表,通过 @TableField表名实体类和表中的字段不一致
*/
@TableName("t_brand")//mybatisPlus的注解,类上面打上表名的注解
public class Brand extends Model {
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 + '\'' +
'}';
}
}
该对象是返回给前台接收的对象。此对象需要两个参数total和rows,因此需要两条sql,一条查询条数,一条查询数据
注意:Brand中还有productType的关联属性,所以要进行手动映射。是对象就用,集合则用。此处是商品分类对象
b.name like CONCAT('%',#{keyword},'%') or b.englishName like CONCAT('%',#{keyword},'%')
查询
新增
编辑
删除
批量删除
男
女
男
女
查询
新增
编辑
删除
批量删除
点击上传
只能上传jpg/png文件,且不超过500kb
树状结构重要的代码
@Service
public class ProductTypeServiceImpl extends ServiceImpl implements IProductTypeService {
//注入mapper对象
@Autowired
private ProductTypeMapper productTypeMapper;
//实现树状结构
@Override
public List treeData() {
//递归方法。查看商品类型数据库表得知pid=0为最上一级,返回前台的都是一级菜单
return treeDataRecursion(0L);
}
/**
* 递归:
* 自己方法里调用自己,但是必须有一个出口:没有儿子就出去;
* 好么:
* 不好,因为每次都要发送sql,就要发送很多的sql:
* 要耗时;数据库的服务器要承受很多的访问量,压力大。
* ====》原因是发送了很多sql,我优化就少发送,至少发送1条。
* @return
*/
public List treeDataRecursion(Long pid){
//拿到所有的一级菜单。调用下面的getAllChildren方法
List allChildren = getAllChildren(pid);
//设置一个出口:没有儿子就不用遍历,直接返回null
if(allChildren==null||allChildren.size()==0){
return null;
}
//否则,就要遍历找到当前对象的所有儿子
for (ProductType child : allChildren) {
//调用自己的方法,找到自己的儿子。
//看数据库表就能明白。根据自己的对象的id找自己的儿子
List 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 getAllChildren(Long pid){
//准备baomidou包的wrapper对象
Wrapper wrapper=new EntityWrapper<>();
//wrapper的eq方法:参数是数据库列名和数据值。查询数据库中列名为pid,并且传进来的参数为pid的数据
wrapper.eq("pid", pid);
//mybatisPlus的selectList方法需要一个wrapper对象
return productTypeMapper.selectList(wrapper);
}
}
递归方式每次都要发送sql,数据库要接收很多的访问量,压力大。循环方式:发送一条sql语句,然后在内存中组装父子关系
@Service
public class ProductTypeServiceImpl extends ServiceImpl implements IProductTypeService {
//注入mapper对象
@Autowired
private ProductTypeMapper productTypeMapper;
//实现树状结构
@Override
public List treeData() {
//循环方法。返回前台的都是一级菜单
return treeDataLoop();
}
/**
* 步骤:循环查询
* 1:先查询出所有的数据
* 2:再组装父子结构
* @return
*/
public List treeDataLoop() {
//返回的一级菜单
List result = new ArrayList<>();
//1.先查询出所有的数据。selectList方法的参数mapper为null即可
List productTypes = productTypeMapper.selectList(null);
//定义一个map集合。参数是id和productType类
Map 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 children = parent.getChildren();
//然后将你自己加进去。你自己是你老子的儿子
children.add(current);
}
}
//返回装好的一级菜单
return result;
}
}