一、基础微服务工程
1.1 创建基础微服务模块tensquare_base
创建过程参考tensquare_common
,此处不再赘述。
1.2 pom.xml
引入依赖
在tensquare_base
中引入jpa
、mysql
以及tensquare_common
等依赖。
全文如下:
<?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>tensquare_parent</artifactId>
<groupId>com.tensquare</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>tensquare_base</artifactId>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-jpa -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.tensquare</groupId>
<artifactId>tensquare_common</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
</project>
1.3 创建启动类
在tensquare_base
中,新建包com.tensquare.base
,建立BaseApplication.java
启动类。
如下:
package com.tensquare.base;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import util.IdWorker;
/**
* Created by me on 2019/6/25.
*/
@SpringBootApplication
public class BaseApplication {
public static void main(String[] args) {
SpringApplication.run(BaseApplication.class);
}
@Bean
public IdWorker idWorker() {
return new IdWorker(1, 1);
}
}
此处通过@Bean
注解,注入IdWorker
对象,其中第一个参数为工作机器ID,第二个参数为业务编码。
1.4 创建配置文件
在resource
目录下,新建application.yml
配置文件,进行基础配置。
如下:
server:
port: 9001
spring:
application:
name: tensquare-base
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/tensquare_base?characterEncoding=utf-8
username: root
password: root
jpa:
database: MYSQL
show-sql: true
# generate-ddl: true
至此,tensquare_base
工程搭建完毕,可以运行BaseApplication.java
,查看效果。
二、标签管理-基本CRUD
2.1 表结构分析
字段名称 | 字段含义 | 字段类型 | 备注 |
---|---|---|---|
id | ID | 文本 | |
name | 标签名称 | 文本 | |
state | 状态 | 文本 | 0:无效 1:有效 |
count | 使用数量 | 整型 | |
fans | 关注数 | 整型 | |
recommend | 是否推荐 | 文本 | 0:不推荐 1:推荐 |
2.2 基本CRUD实现
2.2.1 创建实体类
创建com.tensquare.base
包,在包下创建pojo
包,并创建实体类Label
。
代码如下:
package com.tensquare.base.pojo;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* Created by me on 2019/6/25.
*/
@Entity
@Table(name = "tb_label")
public class Label {
@Id
private String id;
private String labelname;
private String state;
private Long count;
private Long fans;
private String recommend;
// 省略get set方法
}
2.2.2 创建数据访问接口
在com.tensquare.base
下创建dao
包,并创建LabelDao
接口。
代码如下:
package com.tensquare.base.dao;
import com.tensquare.base.pojo.Label;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
/**
* Created by me on 2019/6/25.
*/
public interface LabelDao extends JpaRepository<Label, String>, JpaSpecificationExecutor<Label> {
}
其中:
JpaRepository
:提供了基本的增删改查
JpaSpeccificationExecutor
:用于做复杂的条件查询
2.2.3 创建业务逻辑类
在com.tensquare.base
包下创建service
包,并创建LabelService
类。在该类中,实现基本的增删改查功能。
代码如下:
package com.tensquare.base.service;
import com.tensquare.base.dao.LabelDao;
import com.tensquare.base.pojo.Label;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import util.IdWorker;
import java.util.List;
/**
* Created by me on 2019/6/25.
*/
@Service
@Transactional
public class LabelService {
@Autowired
private LabelDao labelDao;
@Autowired
private IdWorker idWorker;
/**
* 查询所有标签
* @return
*/
public List<Label> findAll() {
return labelDao.findAll();
}
/**
* 根据标签ID查找标签
* @param id
* @return
*/
public Label findById(String id) {
return labelDao.findById(id).get();
}
/**
* 添加标签
* @param label
*/
public void add(Label label) {
label.setId(idWorker.nextId() + "");
labelDao.save(label);
}
/**
* 更新标签
* @param label
*/
public void update(Label label) {
labelDao.save(label);
}
/**
* 根据id删除标签
* @param id
*/
public void deleteById(String id) {
labelDao.deleteById(id);
}
}
2.2.3 创建业务逻辑类
在com.tensquare.base
包下创建controller
包,并创建UserController
类。
代码如下:
package com.tensquare.base.controller;
import com.tensquare.base.pojo.Label;
import com.tensquare.base.service.LabelService;
import entity.Result;
import entity.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* 标签控制层
* Created by me on 2019/6/25.
*/
@CrossOrigin
@RestController
@RequestMapping("/label")
public class LabelController {
@Autowired
private LabelService labelService;
@GetMapping("list")
public Result<List> findAll() {
return new Result<>(true, StatusCode.OK, "success", labelService.findAll());
}
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public Result<Label> findById(@PathVariable String id) {
return new Result<>(true, StatusCode.OK, "success", labelService.findById(id));
}
@RequestMapping(method = RequestMethod.POST)
public Result add(@RequestBody Label label) {
labelService.add(label);
return new Result(true, StatusCode.OK, "添加成功");
}
@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
public Result update(@RequestBody Label label, @PathVariable String id) {
label.setId(id);
labelService.update(label);
return new Result(true, StatusCode.OK, "修改成功");
}
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
public Result deleteById(@PathVariable String id) {
labelService.deleteById(id);
return new Result(true, StatusCode.OK, "删除成功");
}
}
至此,标签的CRUD功能基本完成,接下来可以使用PostMan工具进行测试,此处就不再赘述了。
三、标签管理-复杂查询
在讲了基本CRUD
后,来处理一下实际使用中常见的复杂查询。
3.1 根据条件查询标签列表
3.1.1 修改LabelService
,增加方法
代码如下:
/**
* 根据条件查询标签
*
* @param searchMap
* @return
*/
public List<Label> searchLabel(Map searchMap) {
Specification<Label> specification = createSpecification(searchMap);
return labelDao.findAll(specification);
}
/**
* 根据参数构造查询条件
*
* @param serachMap
* @return
*/
private Specification<Label> createSpecification(Map serachMap) {
return new Specification<Label>() {
@Override
public Predicate toPredicate(Root<Label> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
List<Predicate> predicateList = new ArrayList<>();
// labelname校验
String labelname = (String) serachMap.get("labelname");
if (labelname != null && !"".equals(labelname)) {
predicateList.add(criteriaBuilder.like(root.get("labelname").as(String.class), "%" + labelname + "%"));
}
// state校验
String state = (String) serachMap.get("state");
if (state != null && !"".equals(state)) {
predicateList.add(criteriaBuilder.equal(root.get("state").as(String.class), state));
}
// recommend校验
String recommend = (String) serachMap.get("recommend");
if (recommend != null && !"".equals(recommend)) {
predicateList.add(criteriaBuilder.equal(root.get("recommend").as(String.class), recommend));
}
return criteriaBuilder.and(predicateList.toArray(new Predicate[predicateList.size()]));
}
};
}
3.1.2 修改LabelController
,增加方法
@RequestMapping(value = "/search", method = RequestMethod.POST)
public Result searchLabel(@RequestBody Map searchMap) {
List<Label> labelList = labelService.searchLabel(searchMap);
return Result.ok(labelList);
}
3.2 带分页的条件查询
3.2.1 修改LabelService
在LabelService
类中增加方法,进行分页操作,需要使用到类PageRequest
。
代码如下:
/**
* 带分页的条件查询
*
* @param searchMap 查询条件
* @param page 当前页码
* @param size 每页展示数量
* @return
*/
public Page<Label> findSearch(Map searchMap, int page, int size) {
Specification<Label> specification = createSpecification(searchMap);
// 页码数-1处理
PageRequest pageRequest = PageRequest.of(page - 1, size);
return labelDao.findAll(specification, pageRequest);
}
3.2.2 修改LabelController
增加findSearch
方法,此处就使用到之前在tensquare_common
中定义的PageResult
类了。
代码如下:
@RequestMapping(value = "/search/{page}/{size}", method = RequestMethod.POST)
public Result findSearch(@RequestBody Map searchMap, @PathVariable int page, @PathVariable int size) {
Page<Label> labelPage = labelService.findSearch(searchMap, page, size);
return new Result(true, StatusCode.OK, "查询成功", new PageResult<>(labelPage.getTotalElements(), labelPage.getContent());
}
好了,复杂查询就简单介绍到这了。
四、小结
本篇主要介绍了:
- 创建基础微服务子工程及其配置
- 基本查询
- 复杂查询