商品微服务:
乐优商城是一个全品类的电商购物平台,那么核心自然就是商品,因此搭建商品微服务
ly-item
,包含商品相关的一系列内容的管理,包括:
- 商品分类管理
- 品牌管理
- 商品规格参数管理
- 商品管理
- 库存管理
1 微服务结构
ly-item
是一个微服务,那么将来肯定会有其它系统需要来调用服务中提供的接口,因此肯定也会使用到接口中关联的实体类。
因此这里我们需要使用聚合工程,将要提供的接口及相关实体类放到独立子工程中,以后别人引用的时候,只需要知道坐标即可。
我们会在ly-item中创建两个子工程:
ly-item-interface
:主要是对外暴露的API接口及相关实体类ly-item-service
:所有业务逻辑及内部使用接口
2 父工程的构建
工程结构:
添加依赖:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>leyou</artifactId>
<groupId>com.leyou.parent</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>com.leyou.service</groupId>
<artifactId>ly-item</artifactId>
<!-- 打包方式为pom -->
<packaging>pom</packaging>
<modules>
<module>ly-item-interface</module>
<module>ly-item-service</module>
</modules>
</project>
maven的三种项目打包方式——jar,war,pom的区别
- jar:默认的打包方式,打包成jar用作jar包使用。例如
ly-common
,它就是存放一些其他工程都会使用的类,工具类。我们可以在其他工程的pom文件中去引用它 - war:将会打包成war,发布在服务器上,如网站或服务。例如
leyou-portal
,用户可以通过浏览器直接访问,或者是通过发布服务被别的工程调用 - pom:用在父级工程或聚合工程中,用来做jar包的版本控制,必须指明这个聚合工程的打包方式为pom,例如
leyou
,创建12个model分别为
<modules>
<module>ly-registry</module>
<module>ly-gateway</module>
<module>ly-item</module>
<module>ly-common</module>
<module>ly-upload</module>
<module>ly-search</module>
<module>ly-page</module>
<module>ly-sms</module>
<module>ly-user</module>
<module>ly-auth-center</module>
<module>ly-cart</module>
<module>ly-order</module>
</modules>
同时会自动生成12个独立的maven工程。聚合工程只是用来帮助其他模块构建的工具,本身并没有实质的内容。具体每个工程代码的编写还是在生成的工程中去写。
使用聚合工程leyou
的意义就是:
原本这些模块也是一个个独立的工程,现在将它们聚合到leyou
中,这样我们构建项目的时候就只要构建leyou
一个就行了。我们只要使用maven
构建这个聚合工程就行了而不用去操心模块的构建,比如install时只要install leyou
就行。总之就是简化操作。正常的编码工作还是在对应的maven工程中进行的。
2.1 ly-item-interface
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>ly-item</artifactId>
<groupId>com.leyou.service</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>com.leyou.service</groupId>
<artifactId>ly-item-interface</artifactId>
<dependencies>
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-core</artifactId>
<version>1.0.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<dependency>
<groupId>com.leyou.common</groupId>
<artifactId>ly-common</artifactId>
<version>1.0.0-SNAPSHOT</version>
</dependency>
</dependencies>
</project>
2.2 ly-item-service
2.2.1 添加依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>ly-item</artifactId>
<groupId>com.leyou.service</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<groupId>com.leyou.service</groupId>
<artifactId>ly-item-service</artifactId>
<dependencies>
<!--支持classic和RESTFull的web应用程序启动-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--erueka客户端-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<!--通用mapper启动器-->
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
</dependency>
<!--分页助手启动器-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
</dependency>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.leyou.service</groupId>
<artifactId>ly-item-interface</artifactId>
<version>1.0.0-SNAPSHOT</version>
</dependency>
<!--扫描异常处理的包,包在common下-->
<dependency>
<groupId>com.leyou.common</groupId>
<artifactId>ly-common</artifactId>
<version>1.0.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2.2.2 启动类
@SpringBootApplication
@EnableEurekaClient
@MapperScan("com.leyou.item.mapper")
public class LyItemApplication {
public static void main(String[] args) {
SpringApplication.run(LyItemApplication.class,args);
}
}
2.2.3 配置文件
server:
port: 8081
spring:
application:
name: item-service
datasource:
url: jdbc:mysql://localhost:3306/yun6
username: root
password: 123
rabbitmq:
host: 192.168.124.128
username: ***
password: ***
virtual-host: /***
template:
retry:
enabled: true
initial-interval: 10000ms
max-interval: 300000ms
multiplier: 2
exchange: ly.item.exchange #缺省的交换机名称,此处配置后,发送消息如果不指定交换机就会使用这个
publisher-confirms: true #生产者确认机制,确保消息会正确发送,如果发送失败会有错误回执,从而触发重试
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:10086/eureka
instance:
prefer-ip-address: true
ip-address: 127.0.0.1
mybatis:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
2.2.4 添加商品微服务的路由规则
zuul:
prefix: /api # 添加路由前缀
retryable: true
routes:
item-service: /item/** # 将商品微服务映射到/item/**
项目基本搭建到此结束。
2.3 实现域名访问
2.3.1 域名解析过程
域名解析过程:
- 本地域名解析
浏览器会首先在本机的hosts文件中查找域名映射的IP地址,如果查找到就返回IP ,没找到则进行域名服务器解析 - 域名服务器解析
本地解析失败,才会进行域名服务器解析,域名服务器就是网络中的一台计算机,里面记录了所有注册备案的域名和ip映射关系,一般只要域名是正确的,并且备案通过,一定能找到。
因此,我们修改本地hosts文件,实现对域名的解析。
2.3.2 nginx
虽然域名解决了,但是现在如果我们要访问,还得自己加上端口:http://manage.leyou.com:9001
,直接访问域名,这种情况下默认端口是80,将80端口的请求转移到9001就需要反向代理工具——nginx。
nginx是什么
- nginx是一个高性能的web和反向代理服务器(由C编写)
- 作为web服务器:使用更少的资源支持更高并发连接,数量高达50000
- 作为负载均衡服务器:既可以内部直接支持Rails也可以支持作为http代理服务器对外进行服务
- 作为邮件代理服务器
nginx可以作为web服务器,但更多的时候,我们把它作为网关,因为它具备网关必备的功能:
- 反向代理
- 负载均衡
- 动态路由
- 请求过滤
web服务器和web应用服务器:
web应用服务器,如:
- tomcat
- resin
- jetty
web服务器,如:
- Apache 服务器
- Nginx
- IIS
区分:web服务器不能解析jsp等页面,只能处理js、css、html等静态资源。
并发:web服务器的并发能力远高于web应用服务器。
2.3.3 nginx作为反向代理服务器
什么是反向代理?
- 代理:通过客户机的配置,实现让一台服务器代理客户机,客户的所有请求都交给代理服务器处理。
- 反向代理:用一台服务器,代理真实服务器,用户访问时,不再是访问真实服务器,而是代理服务器。
nginx可以当做反向代理服务器来使用:
- 我们需要提前在nginx中配置好反向代理的规则,不同的请求,交给不同的真实服务器处理
- 当请求到达nginx,nginx会根据已经定义的规则进行请求的转发,从而实现路由功能
原理图1:
原理图2:
原理图3:
2.4 实现商品分类查询
2.4.1 实体类
@Table(name = "tb_category")
@Data
public class Category {
@Id
//声明一个实体类的属性映射为数据库的主键列
@KeySql(useGeneratedKeys=true)
//使用 JDBC 方式获取主键,优先级最高,设置为 true 后,不对其他配置校验
private Long id;
private String name;
private Long parentId;
private Boolean isParent;
private Integer sort;
@Transient //修饰的字段不会被持久化
private List<Category> categoryList;
}
上述注解都是JPA的依赖,而通用mapper的底层依赖了JPA
因此interface
中引入mapper-core
依赖就可以。
@Table
:
当实体类与其映射的数据库表名不同名时需要使用 @Table 标注说明,name属性用于指定数据库表名称,若不指定则以实体类名称作为表名。
例如实体类为Category
,是数据库中表名为tb_category
持久化与映射:
- 持久化(JPA,Java Persistence API):
- 用来操作实体对象,执行CRUD操作,框架在后台替我们完成所有的事情,开发者从繁琐的JDBC和SQL代码中解脱出来
- 将运行期的实体对象持久化到数据库中。
- 通过面向对象而非面向数据库的查询语言查询数据,避免程序的SQL语句紧密耦合
- 映射(ORM):
- ORM(Object-Relation-Mapping),即对象关系映射技术,是对象持久化的核心
2.4.2 mapper
public interface CategoryMapper extends Mapper<Category> {
}
2.4.3 controller
@RestController
@RequestMapping("category")
//这个注解会将 HTTP 请求映射到 MVC 和 REST 控制器的处理方法上。
//就是控制方法的URL地址
public class CategoryController {
@Autowired
private CategoryService categoryService;
/**
* 根据pid查询商品种类
* @param pid
* @return
*/
@GetMapping("list")
//@GetMapping是一个组合注解,是@RequestMapping(method = RequestMethod.GET)的缩写。
public ResponseEntity<List<Category>> queryCategoryListByPid(@RequestParam("pid")Long pid){
return ResponseEntity.ok(categoryService.queryCategoryListByPid(pid));
}
}
2.4.4 service
@Service
public class CategoryService {
@Autowired
private CategoryMapper categoryMapper;
/**
* 查询商品分类的方法
* @param pid
* @return
*/
public List<Category> queryCategoryListByPid(Long pid) {
//查询的对象需要自己new出来,并将这个对象中的非空字段作为查询条件
Category t = new Category();
t.setParentId(pid);
List<Category> list = categoryMapper.select(t);
if(CollectionUtils.isEmpty(list)){
throw new LyException(ExceptionEnum.CATEGORY_NOT_FOUND);
}
return list;
}
}
2.5 跨域问题
通过域名访问却报了上述的错误,原因就是——跨域问题。
2.5.1 什么是跨域
跨域原因说明 | 示例 |
---|---|
域名不同 | www.jd.com 与 www.taobao.com |
域名相同,端口不同 | www.jd.com:8080 与 www.jd.com:8081 |
二级域名不同 | item.jd.com 与 miaosha.jd.com |
如果域名和端口都相同,但是请求路径不同,不属于跨域,如:
www.jd.com/item
www.jd.com/goods
而我们刚才是从manage.leyou.com
去访问api.leyou.com
,这属于二级域名不同,跨域了。
2.5.2 为什么会有跨域问题
跨域问题是浏览器对于ajax请求的一种安全限制:一个页面发起的ajax请求,只能是于当前页同域名的路径,这能有效的阻止跨站攻击。
因此:跨域问题 是针对ajax的一种限制。
2.5.3 解决跨域问题方案
-
Jsonp
最早的解决方案,利用script标签可以跨域的原理实现。
限制:
- 需要服务的支持
- 只能发起GET请求
-
nginx反向代理
思路是:利用nginx反向代理把跨域为不跨域,支持各种请求方式
缺点:需要在nginx进行额外配置,语义不清晰
-
CORS
规范化的跨域请求解决方案,安全可靠。
优势:
- 在服务端进行控制是否允许跨域,可自定义规则
- 支持各种请求方式
缺点:
- 会产生额外的请求
我们这里会采用cors的跨域方案。
该方案需要浏览器和服务器同时支持。目前,所有浏览器都支持该功能,IE浏览器不能低于IE10。
-
浏览器端:
目前,所有浏览器都支持该功能(IE10以下不行)。整个CORS通信过程,都是浏览器自动完成,不需要用户参与。
-
服务端:
CORS通信与AJAX没有任何差别,因此你不需要改变以前的业务逻辑。只不过,浏览器会在请求中携带一些头信息,我们需要以此判断是否运行其跨域,然后在响应头中加入一些信息即可。这一般通过过滤器完成即可。
2.5.4 跨域原理
浏览器会将ajax请求分为两类,其处理方案略有差异:简单请求、特殊请求。
简单请求
只要同时满足以下两大条件,就属于简单请求:
(1) 请求方法是以下三种方法之一:
- HEAD
- GET
- POST
(2)HTTP的头信息不超出以下几种字段:
- Accept:请求头用来告知客户端可以处理的内容类型,这种内容类型用MIME类型来表示。
- Accept-Language:用来说明访问者希望采用的语言或语言组合
- Content-Language:访问者希望采用的语言或语言组合
- Last-Event-ID
- Content-Type:只限于三个值
application/x-www-form-urlencoded
、multipart/form-data
、text/plain
当浏览器发现发现的ajax请求是简单请求时,会在请求头中携带一个字段:Origin
.
Origin中会指出当前请求属于哪个域(协议+域名+端口)。服务会根据这个值决定是否允许其跨域。
如果服务器允许跨域,需要在返回的响应头中携带下面信息:
Access-Control-Allow-Origin: http://manage.leyou.com
Access-Control-Allow-Credentials: true
Content-Type: text/html; charset=utf-8
- Access-Control-Allow-Origin:可接受的域,是一个具体域名或者*,代表任意
- Access-Control-Allow-Credentials:是否允许携带cookie,默认情况下,cors不会携带cookie,除非这个值是true
获取origin步骤:request->header->origin
特殊请求
不符合简单请求的条件,会被浏览器判定为特殊请求,,例如请求方式为PUT。
预检请求
特殊请求会在正式通信之前,增加一次HTTP查询请求,称为"预检"请求(preflight)。
浏览器先询问服务器,当前网页所在的域名是否在服务器的许可名单之中,以及可以使用哪些HTTP动词和头信息字段。只有得到肯定答复,浏览器才会发出正式的XMLHttpRequest
请求,否则就报错。
一个“预检”请求的样板:
OPTIONS /cors HTTP/1.1
Origin: http://manage.leyou.com
Access-Control-Request-Method: PUT
Access-Control-Request-Headers: X-Custom-Header
Host: api.leyou.com
Accept-Language: en-US
Connection: keep-alive
User-Agent: Mozilla/5.0...
与简单请求相比,除了Origin以外,多了两个头:
- Access-Control-Request-Method:接下来会用到的请求方式,比如PUT
- Access-Control-Request-Headers:会额外用到的头信息
预检请求的响应
服务的收到预检请求,如果许可跨域,会发出响应:
HTTP/1.1 200 OK
Date: Mon, 01 Dec 2008 01:15:39 GMT
Server: Apache/2.0.61 (Unix)
Access-Control-Allow-Origin: http://manage.leyou.com
Access-Control-Allow-Credentials: true //是否允许携带cookie
Access-Control-Allow-Methods: GET, POST, PUT
Access-Control-Allow-Headers: X-Custom-Header
Access-Control-Max-Age: 1728000
Content-Type: text/html; charset=utf-8
Content-Encoding: gzip
Content-Length: 0
Keep-Alive: timeout=2, max=100
Connection: Keep-Alive
Content-Type: text/plain
除了Access-Control-Allow-Origin
和Access-Control-Allow-Credentials
以外,这里又额外多出3个头:
- Access-Control-Allow-Methods:允许访问的方式
- Access-Control-Allow-Headers:允许携带的头
- Access-Control-Max-Age:本次许可的有效时长,单位是秒,过期之前的ajax请求就无需再次进行预检了
如果浏览器得到上述响应,则认定为可以跨域,后续就跟简单请求的处理是一样的了。
2.5.5 跨域的实现
- 浏览器端都有浏览器自动完成,我们无需操心
- 服务端可以通过拦截器统一实现,不必每次都去进行跨域判定的编写。
事实上,SpringMVC已经帮我们写好了CORS的跨域过滤器:CorsFilter ,内部已经实现了刚才所讲的判定逻辑,我们直接用就好了。
在ly-api-gateway
中编写一个配置类,并且注册CorsFilter:
@Configuration
public class GlobalCorsConfig {
@Bean
public CorsFilter corsFilter() {
//1.添加CORS配置信息
CorsConfiguration config = new CorsConfiguration();
//1) 允许的域,不要写*,否则cookie就无法使用了(因为写了*代表一切请求都可以跨域,cookie就已经不安全了)
config.addAllowedOrigin("http://manage.leyou.com");
//2) 是否发送Cookie信息
config.setAllowCredentials(true);
//3) 允许的请求方式
config.addAllowedMethod("OPTIONS");
config.addAllowedMethod("HEAD");
config.addAllowedMethod("GET");
config.addAllowedMethod("PUT");
config.addAllowedMethod("POST");
config.addAllowedMethod("DELETE");
config.addAllowedMethod("PATCH");
// 4)允许的头信息
config.addAllowedHeader("*");
//2.添加映射路径,我们拦截一切请求
UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
configSource.registerCorsConfiguration("/**", config);
//3.返回新的CorsFilter.
return new CorsFilter(configSource);
}
}
重新访问,ok!
2.6 实现品牌查询
可以看出:
- 请求的方式:get
- 请求的路径:brand/page
- 请求的参数:
- page:当前页,int
- rows:每页大小,int
- sortBy:排序字段,String
- desc:是否为降序,boolean
- key:搜索关键词,String
- 响应结果:
- total:总条数
- items:当前页数据
- totalPage:有些还需要总页数
2.6.1 实体类
@Data
@Table(name="tb_brand")
public class Brand {
@Id
@KeySql(useGeneratedKeys = true)
private Long id;
private String name;
private Character letter;
private String image;
}
品牌和商品分类是多对多关系,有一张中间表tb_category_brand
,但是这张表没有设置外键约束,这是因为电商中更注重性能,电商中需要频繁的增删改查操作,设置外键影响数据库读写的效率,并且数据删除时会很麻烦。既然没有设置外键那么只能靠代码来维护关系。
2.6.2 返回结果的封装
后续需要频繁的查询,很多微服务也要使用这个返回结果封装,因此把这个类放到ly-common下
@Data
public class PageResult<T> {
private Long total;//总条数
private Integer totalPage;//总页数
private List<T> items;
public PageResult() {
}
public PageResult(Long total, List<T> items) {
this.total = total;
this.items = items;
}
public PageResult(Long total, Integer totalPage, List<T> items) {
this.total = total;
this.totalPage = totalPage;
this.items = items;
}
}
2.6.3 mapper
public interface BrandMapper extends Mapper<Brand> {
}
2.6.4 controller
@RestController
@RequestMapping("brand")
public class BrandController {
@Autowired
private BrandService brandService;
//分页查询品牌
@GetMapping("page")
public ResponseEntity<PageResult<Brand>> queryBrandByPage(
@RequestParam(value = "page" , defaultValue = "1") Integer page,
@RequestParam(value = "rows" , defaultValue = "5") Integer rows,
@RequestParam(value = "sortBy" , required = false) String sortBy,
@RequestParam(value = "desc" , defaultValue = "false") boolean desc,
@RequestParam(value = "key" , required = false) String key
){
PageResult<Brand> result = brandService.queryBrandByPage(page,rows,sortBy,desc,key);
return ResponseEntity.ok(result);
}
}
@RequestParam:
注解主要参数:
-
value:参数名字,即入参的请求参数名字
-
required:是否必须,默认是true,表示请求中一定要有相应的参数,否则将报404错误码;
-
defaultValue:默认值,表示如果请求中没有同名参数时的默认值
在SpringMVC后台控制层获取参数的方式主要有两种:
equest.getParameter("name")
- 用注解
@RequestParam
直接获取
@PathVariable:
-
@PathVariable
是用来获得请求url中的动态参数的 -
@PathVariable
用于将请求URL中的模板变量映射到功能处理方法的参数上。//配置url和方法的一个关系@RequestMapping("item/{itemId}")
通俗来说,@PathVariable
是路径占位符,获取URL中/
之间的动态参数,@RequestParam
是获取URL中/路径?参数=值
中的参数,简而言之,如果路径最后有?
用@RequestParam
,最后是/参数
用@PathVariable
2.6.5 service
@Service
public class BrandService {
@Autowired
private BrandMapper brandMapper;
// 根据多个条件查询品牌信息
public PageResult<Brand> queryBrandByPage(Integer page, Integer rows, String sortBy, boolean desc, String key) {
//分页
PageHelper.startPage(page,rows);
//过滤: 过滤条件(模糊查询+准确查询(首字母))
Example example = new Example(Brand.class);
if(StringUtils.isNotBlank(key)){
example.createCriteria().orLike("name","%"+key+"%").orEqualTo("letter",key.toUpperCase());
}
//排序
if(StringUtils.isNotBlank(sortBy)){
String orderByClause = sortBy + (desc ? " DESC" : " ASC");
example.setOrderByClause(orderByClause);
}
//查询
List<Brand> list = brandMapper.selectByExample(example);
if(CollectionUtils.isEmpty(list)){
throw new LyException(ExceptionEnum.BRAND_NOT_FOUND);
}
//解析分页结果
PageInfo<Brand> pageInfo = new PageInfo<>(list);
return new PageResult<>(pageInfo.getTotal(),list);
}
}
- 分页
PageHelper.startPage(page,rows);
语句会利用mybatis
的拦截器对接下来的sql
语句进行拦截,自动在该sql后面动态拼接sql语句,如上述方法中的拼接limit
语句。
- 过滤
Example example = new Example(Brand.class);
将Brand.class
字节码文件传给Example,通过反射得到实体类中的表的名字,主键等信息。example.createCriteria().orLike("name","%"+key+"%").orEqualTo("letter",key.toUpperCase());
源码如下,相当于动态and拼接sql语句
之后拼接模糊查询语句:
准确查询语句:
因为是或关系,所以用or- 相关知识参考博客:Mybatis中的example类的使用
- 排序
example.setOrderByClause(orderByClause);
ORDER BY关键字是可以自动生成的,重点是后面的 根据什么排序 sql语句不知道,所以要写一个orderByClause——排序子句
注意:" DESC" : " ASC"
关键字前要有空格,否则拼起来就是ORDER BYDESC,正确的是ORDER BY DESC
- 查询
List<Brand> list = brandMapper.selectByExample(example);
- 解析分页结果
-
PageInfo<Brand> pageInfo = new PageInfo<>(list);
return new PageResult<>(pageInfo.getTotal(),list);
分页助手会对list做一个拦截,将list转换成一个Page对象,Page就是一个list集合,里面有当前页信息等等…所以可以对list进行分页解析
-
2.7 实现品牌新增
前台页面信息:
请求方式:post
请求路径:/brand
请求参数:Brand类
,cids
返回值:无
2.7.1 mapper
中间表新增
通用Mapper只能处理单表,也就是Brand的数据但是中间表没有实体类,没有通用mapper,因此要自己写sql语句!
public interface BrandMapper extends BaseMapper<Brand> {
@Insert("INSERT INTO tb_category_brand (category_id, brand_id) VALUES (#{cid},#{bid})")
//@Param是mybatis中的注解,用注解来简化xml配置的时候,
// @Param注解的作用是给参数命名,参数命名后就能根据名字得到参数值,正确的将参数传入sql语句中
int insertCategoryBrand(@Param("cid") Long cid, @Param("bid")Long bid);
}
2.7.2 controller
@PostMapping
public ResponseEntity<Void> saveBrand(Brand brand,@RequestParam("cids")List<Long> cids){
//RequestParam可以接受简单类型的属性,也可以接受对象类型.get 方式中queryString的值,和post方式中 body data的值都会被Servlet接受到并转化到Request.getParameter()参数集中,所以@RequestParam可以获取的到
brandService.saveBrand(brand,cids);
return ResponseEntity.status(HttpStatus.CREATED).build();//无返回体选择build
}
2.7.3 service
@Transactional
public void saveBrand(Brand brand, List<Long> cids) {
//新增品牌
brand.setId(null);//初始设置成null,新增之后回显
int count = brandMapper.insert(brand);
if(count != 1){
throw new LyException(ExceptionEnum.BRAND_CREATE_FAILED);
}
//中间表新增。但是中间表没有实体类,没有通用mapper
for (Long cid : cids){
count = brandMapper.insertCategoryBrand(cid,brand.getId());
if(count != 1){
throw new LyException(ExceptionEnum.BRAND_CREATE_FAILED);
}
}
}
@Transactional
- 在配置文件中做相关的事务规则声明(或通过基于@Transactional注解的方式),便可以将事务规则应用到业务逻辑中
- 声明式事务管理也有两种常用的方式,一种是基于tx和aop名字空间的xml配置文件,另一种就是基于@Transactional注解
- 当作用于类上时,该类的所有 public 方法将都具有该类型的事务属性,同时,我们也可以在方法级别使用该标注来覆盖类级别的定义
- 如果被注解的数据库操作方法中发生了unchecked异常,所有的数据库操作将rollback
声明式事务管理建立在AOP之上的。其本质是对方法前后进行拦截,然后在目标方法开始之前创建或者加入一个事务,在执行完目标方法之后根据执行情况提交或者回滚事务。
相关资料:spring的@Transactional注解详细用法
sql语句中#{}和${}的区别
#{}
#
将传入的数据都当成一个字符串,会对自动传入的数据加一个双引号
eg:
order by #user_id#
如果传入的值是111,那么解析成sql时的值为order by “111”
如果传入的值是id,则解析成的sql为order by “id”
${}
$
将传入的数据直接显示生成在sql中
eg:
order by userid
如果传入的值是111,那么解析成sql时的值为order by 111
如果传入的值是id,则解析成的sql为order by id
结论:
#
方式底层采用预编译方式PreparedStatement
(预编译),能够很大程度防止sql注入;$
方式底层只是Statement
,无法防止Sql注入
$
方式一般用于传入数据库对象,例如传入表名.
一般能用#
的就别用$
注意点:
MyBatis排序时使用order by 动态参数时需要注意,用**$**而不是#
参考资料:sql 中 ${} 和 #{}的区别
最后,图片上传见 上传微服务
over !
2.8 实现图片上传
文件上传单独创建一个微服务,笔记:上传微服务笔记
2.9 商品表结构的分析
数据库的设计思路:笔记:商品微服务的构建与商品表结构分析
2.10 实现商品规格参数的管理
2.10.1 规格组的查询
2.10.1.1 实体类
@Data
@Table(name = "tb_spec_group")
public class SpecGroup {
@Id
@KeySql(useGeneratedKeys = true)
private Long id;
private Long cid;
private String name;
@Transient
private List<SpecParam> params; // 该组下的所有规格参数集合
}
2.10.1.2 mapper
public interface SpecGroupMapper extends Mapper<SpecGroup> {
}
2.10.1.3 controller
请求方式:get
请求路径:/spec/groups/cid
返回结果:group的集合
@RestController
@RequestMapping("spec")
public class SpecificationController {
@Autowired
private SpecificationService specificationService;
@GetMapping("groups/{cid}")
public ResponseEntity<List<SpecGroup>> queryGroupByCid(@PathVariable("cid")Long cid){
return ResponseEntity.ok(specificationService.queryGroupByCid(cid));
}
}
2.10.1.4 service
public List<SpecGroup> queryGroupByCid(Long cid) {
SpecGroup group = new SpecGroup();
group.setCid(cid);
//根据非空字段进行查询
List<SpecGroup> list = groupMapper.select(group);
if(CollectionUtils.isEmpty(list)){
throw new LyException(ExceptionEnum.GROUP_NOT_FOUND);
}
return list;
}
2.10.2 规格参数查询
点击组名可以查看组内参数。
2.10.2.1 实体类
@Data
@Table(name = "tb_spec_param")
public class SpecParam {
@Id
@KeySql(useGeneratedKeys = true)
private Long id;
private Long cid;
private Long groupId;
private String name;
@Column(name = "`numeric`")//通用mapper生成sql语句时,不要直接拼接numeric,而要拼接`numeric`,加上``变成普通字符串,numeric是一个关键字
private Boolean numeric;
private String unit;
private Boolean generic;
private Boolean searching;
private String segments;
}
2.10.2.2 mapper
public interface SpecParamMapper extends Mapper<SpecParam> {
}
2.10.2.3 controller
请求方式:get
请求路径:/spec/params(根据组Id来查)
返回结果:当前组下的所有规格参数
@GetMapping("/params")
public ResponseEntity<List<SpecParam>> querySpecParams(@RequestParam(value = "gid",required = false)Long gid
//@RequestParam(value = "cid",required = false)Long cid,
//@RequestParam(value = "searching",required = false)Boolean searching){
return ResponseEntity.ok(specificationService.querySpecParams(gid/*cid,searching)*/);
}
2.10.2.4 service
public List<SpecParam> querySpecParams(Long gid, Long cid, Boolean searching) {
SpecParam param = new SpecParam();
param.setGroupId(gid);
//param.setCid(cid);
//param.setSearching(searching);
List<SpecParam> params = paramMapper.select(param);
if(CollectionUtils.isEmpty(params)){
throw new LyException(ExceptionEnum.GROUP_PARAM_NOT_FOUND);
}
return params;
}
2.11 实现商品查询
2.11.1 实体类
spu:
@Data
@Table(name = "tb_spu")
public class Spu {
@Id
@KeySql(useGeneratedKeys = true)
private Long id;
private Long brandId;
private Long cid1;// 1级类目
private Long cid2;// 2级类目
private Long cid3;// 3级类目
private String title;// 标题
private String subTitle;// 子标题
private Boolean saleable;// 是否上架
@JsonIgnore
private Boolean valid;// 是否有效,逻辑删除用
private Date createTime;// 创建时间
@JsonIgnore//返回时可以忽略这个字段
private Date lastUpdateTime;// 最后修改时间
//po是持久层数据,vo是new出来中间是程序使用的,隐私数据不能暴露
@Transient
private String cname;//这两个字段不是数据库字段,但是放在这里通用mapper会把它当成数据库字段,所以要添加一个注解
@Transient
private String bname;
@Transient
private List<Sku> skus;
@Transient
private SpuDetail spuDetail;
}
spu_detail:
@Data
@Table(name="tb_spu_detail")
public class SpuDetail {
@Id
private Long spuId;// 对应的SPU的id
private String description;// 商品描述
private String specialSpec;// 商品特殊规格的名称及可选值模板
private String genericSpec;// 商品的全局规格属性
private String packingList;// 包装清单
private String afterService;// 售后服务
}
sku:
@Data
@Table(name = "tb_sku")
public class Sku {
@Id
@KeySql(useGeneratedKeys = true)
private Long id;
private Long spuId;
private String title;
private String images;
private Long price;
private String ownSpec;// 商品特殊规格的键值对
private String indexes;// 商品特殊规格的下标
private Boolean enable;// 是否有效,逻辑删除用
private Date createTime;// 创建时间
private Date lastUpdateTime;// 最后修改时间
@Transient
private Integer stock;// 库存
}
2.11.2 mapper
spuMapper:
public interface SpuMapper extends Mapper<Spu>{
}
spuDetailMapper:
public interface SpuDetailMapper extends BaseMapper<SpuDetail> {
}
skuMapper:
public interface SkuMapper extends BaseMapper<Sku>{
}
2.11.3 controller
@GetMapping("/spu/page")
public ResponseEntity<PageResult<Spu>> querySpuByPage(
@RequestParam(value = "page",defaultValue = "1")Integer page,
@RequestParam(value = "rows",defaultValue = "5")Integer rows,
@RequestParam(value = "saleable",required = false)Boolean saleable,
@RequestParam(value = "key",required = false)String key
){
return ResponseEntity.ok(goodsService.querySpuByPage(page,rows,saleable,key));
}
2.11.4 service
public PageResult<Spu> querySpuByPage(Integer page, Integer rows, Boolean saleable, String key) {
//分页
PageHelper.startPage(page,rows);
//过滤
Example example = new Example(Spu.class);
Example.Criteria criteria = example.createCriteria();
//搜索字段过滤
if(StringUtils.isNotBlank(key))
criteria.andLike("title","%"+key+"%");
//上下架过滤
if(saleable!=null)
criteria.andEqualTo("saleable",saleable);
//默认排序
example.setOrderByClause("last_update_time DESC");
//查询
List<Spu> spus = spuMapper.selectByExample(example);
if(CollectionUtils.isEmpty(spus))
throw new LyException(ExceptionEnum.GOODS_SAVE_ERROR);
//解析分类和品牌名称--因为前台页面需要的是分类名称和品牌名称而非id
loadCategoryAndBrandName(spus);
//解析分页结果
PageInfo<Spu> pageInfo = new PageInfo<>(spus);
return new PageResult<>(pageInfo.getTotal(),spus);
}
//解析分类和品牌名称
private void loadCategoryAndBrandName(List<Spu> spus) {
for (Spu spu : spus) {
//处理分类名称
List<String> names = categoryService.queryByIds(Arrays.asList(spu.getCid1(), spu.getCid2(), spu.getCid3()))
.stream().map(Category::getName).collect(Collectors.toList());
spu.setCname(StringUtils.join(names,"/"));
//处理品牌名称
spu.setBname(brandService.queryById(spu.getBrandId()).getName());
}
}
public List<Category> queryByIds(List<Long> cids){
List<Category> idList = categoryMapper.selectByIdList(cids);
if(CollectionUtils.isEmpty(idList)){
throw new LyException(ExceptionEnum.CATEGORY_NOT_FOUND);
}
return idList;
}
public Brand queryById(Long id){
Brand brand = brandMapper.selectByPrimaryKey(id);
if(brand == null){
throw new LyException(ExceptionEnum.BRAND_NOT_FOUND);
}
return brand;
}
结果:
ok!
下半部分见:商品微服务(下)