十次方微服务项目实战03--基础微服务模块搭建及基本CRUD复杂查询

本文主要是介绍十次方微服务项目实战03--基础微服务模块搭建及基本CRUD复杂查询,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

一、基础微服务工程

1.1 创建基础微服务模块tensquare_base

创建过程参考tensquare_common,此处不再赘述。

1.2 pom.xml引入依赖

tensquare_base中引入jpamysql以及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);}@Beanpublic IdWorker idWorker() {return new IdWorker(1, 1);}}

此处通过@Bean注解,注入IdWorker对象,其中第一个参数为工作机器ID,第二个参数为业务编码。

1.4 创建配置文件

resource目录下,新建application.yml配置文件,进行基础配置。
如下:

server:port: 9001
spring:application:name: tensquare-basedatasource:driver-class-name: com.mysql.jdbc.Driverurl: jdbc:mysql://localhost:3306/tensquare_base?characterEncoding=utf-8username: rootpassword: rootjpa:database: MYSQLshow-sql: true
#    generate-ddl: true

至此,tensquare_base工程搭建完毕,可以运行BaseApplication.java,查看效果。

二、标签管理-基本CRUD

2.1 表结构分析

字段名称字段含义字段类型备注
idID文本
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 {@Idprivate 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 {@Autowiredprivate LabelDao labelDao;@Autowiredprivate 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 {@Autowiredprivate 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>() {@Overridepublic 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());}

好了,复杂查询就简单介绍到这了。

四、小结

本篇主要介绍了:

  • 创建基础微服务子工程及其配置
  • 基本查询
  • 复杂查询

这篇关于十次方微服务项目实战03--基础微服务模块搭建及基本CRUD复杂查询的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/982415

相关文章

MySQL 中的 JSON 查询案例详解

《MySQL中的JSON查询案例详解》:本文主要介绍MySQL的JSON查询的相关知识,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录mysql 的 jsON 路径格式基本结构路径组件详解特殊语法元素实际示例简单路径复杂路径简写操作符注意MySQL 的 J

Go语言开发实现查询IP信息的MCP服务器

《Go语言开发实现查询IP信息的MCP服务器》随着MCP的快速普及和广泛应用,MCP服务器也层出不穷,本文将详细介绍如何在Go语言中使用go-mcp库来开发一个查询IP信息的MCP... 目录前言mcp-ip-geo 服务器目录结构说明查询 IP 信息功能实现工具实现工具管理查询单个 IP 信息工具的实现服

Python的time模块一些常用功能(各种与时间相关的函数)

《Python的time模块一些常用功能(各种与时间相关的函数)》Python的time模块提供了各种与时间相关的函数,包括获取当前时间、处理时间间隔、执行时间测量等,:本文主要介绍Python的... 目录1. 获取当前时间2. 时间格式化3. 延时执行4. 时间戳运算5. 计算代码执行时间6. 转换为指

SpringBoot基于配置实现短信服务策略的动态切换

《SpringBoot基于配置实现短信服务策略的动态切换》这篇文章主要为大家详细介绍了SpringBoot在接入多个短信服务商(如阿里云、腾讯云、华为云)后,如何根据配置或环境切换使用不同的服务商,需... 目录目标功能示例配置(application.yml)配置类绑定短信发送策略接口示例:阿里云 & 腾

Python正则表达式语法及re模块中的常用函数详解

《Python正则表达式语法及re模块中的常用函数详解》这篇文章主要给大家介绍了关于Python正则表达式语法及re模块中常用函数的相关资料,正则表达式是一种强大的字符串处理工具,可以用于匹配、切分、... 目录概念、作用和步骤语法re模块中的常用函数总结 概念、作用和步骤概念: 本身也是一个字符串,其中

Python中的getopt模块用法小结

《Python中的getopt模块用法小结》getopt.getopt()函数是Python中用于解析命令行参数的标准库函数,该函数可以从命令行中提取选项和参数,并对它们进行处理,本文详细介绍了Pyt... 目录getopt模块介绍getopt.getopt函数的介绍getopt模块的常用用法getopt模

springboot项目如何开启https服务

《springboot项目如何开启https服务》:本文主要介绍springboot项目如何开启https服务方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录springboot项目开启https服务1. 生成SSL证书密钥库使用keytool生成自签名证书将

MySQL索引的优化之LIKE模糊查询功能实现

《MySQL索引的优化之LIKE模糊查询功能实现》:本文主要介绍MySQL索引的优化之LIKE模糊查询功能实现,本文通过示例代码给大家介绍的非常详细,感兴趣的朋友一起看看吧... 目录一、前缀匹配优化二、后缀匹配优化三、中间匹配优化四、覆盖索引优化五、减少查询范围六、避免通配符开头七、使用外部搜索引擎八、分

Android Mainline基础简介

《AndroidMainline基础简介》AndroidMainline是通过模块化更新Android核心组件的框架,可能提高安全性,本文给大家介绍AndroidMainline基础简介,感兴趣的朋... 目录关键要点什么是 android Mainline?Android Mainline 的工作原理关键

Python列表去重的4种核心方法与实战指南详解

《Python列表去重的4种核心方法与实战指南详解》在Python开发中,处理列表数据时经常需要去除重复元素,本文将详细介绍4种最实用的列表去重方法,有需要的小伙伴可以根据自己的需要进行选择... 目录方法1:集合(set)去重法(最快速)方法2:顺序遍历法(保持顺序)方法3:副本删除法(原地修改)方法4: