十次方微服务项目实战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);
    }

    @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 表结构分析

字段名称字段含义字段类型备注
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 {

    @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());
    }

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

四、小结

本篇主要介绍了:

  • 创建基础微服务子工程及其配置
  • 基本查询
  • 复杂查询
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值