1)、 按照条件查询标签:

① 在controller种添加方法
【确保表中有数据】
/**
     * 根据条件查询
     */
    @PostMapping("/search")
    public Result findSearch(@RequestBody Label label){
        List<Label> list = service.findSearch(label);
        return new Result(true,StatusCode.OK,"查询成功",list);
    }
② 在service 中完善方法
/**
     * 根据条件查询标签
     */
public List<Label> findSearch(Label label) {

    //用到了dao的findAll()的重载方法 传入的参数是Specification的对象,写一个匿名内部类
    return labelDao.findAll(new Specification<Label>() {
            /**
             *
             * @param root 根对象,也就是把哪个对象封装到条件中 where label.id = id
             * @param criteriaQuery  封装的都是查询关键字 例如 group by order by
             * @param cb 用来封装条件对象的
             * @return
             */
        @Override
        public Predicate toPredicate(Root<Label> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder cb) {
            ArrayList list = new ArrayList();
            if (label.getLabelname() != null && !"".equals(label.getLabelname())) {
                Predicate predicate = cb.like(root.get("labelname").as(String.class), "%" + label.getLabelname() + "%");//where labelname like "小明"
                list.add(predicate);
            }
            if (label.getId() != null && !"".equals(label.getId())) {
                Predicate predicate = cb.equal(root.get("id").as(String.class), label.getId());
                list.add(predicate);
            }
            Predicate[] pre = new Predicate[list.size()];
            list.toArray(pre);
            return cb.and(pre);
        }
    });
}
③ 在API中进行测试
 # 根据A模糊查询
{
  "labelname": "A"
}

返回结果:
{
  "flag": true,
  "code": 20000,
  "message": "查询成功",
  "data": [
    {
      "id": "1098215343807037440",
      "labelname": "JAVA",
      "state": "1",
      "count": 0,
      "fans": null,
      "recommend": "1"
    }
  ]
}

2)、根据含分页条件查询标签

①contrller添加方法,注意请求方式及路径
【确保表中有数据】
/**
     * 根据条件查询 含分页信息
     */
    @PostMapping("/search/{page}/{size}")
    public Result queryPage(@RequestBody Label label,@PathVariable int page,@PathVariable int size){
        Page pageData = service.queryPage(label,page,size);
        return new Result(true,StatusCode.OK,"查询成功",new PageResult<>(pageData.getTotalElements(),pageData.getContent()))

    }
② 完善service层的方法
    /**
     * 含有分页条件的查询
     * 使用到了Pageable这一工具
     * 注意page-1
     */

public Page queryPage(Label label, int page, int size) {
        Pageable pageable = PageRequest.of(page-1,size);
        return labelDao.findAll(new Specification<Label>() {
            @Override
            public Predicate toPredicate(Root<Label> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder cb) {
                ArrayList list = new ArrayList();
                if (label.getLabelname() != null && !"".equals(label.getLabelname())) {
                    Predicate predicate = cb.like(root.get("labelname").as(String.class), "%" + label.getLabelname() + "%");//where labelname like "小明"
                    list.add(predicate);
                }
                if (label.getState() != null && !"".equals(label.getState())) {
                    Predicate predicate = cb.equal(root.get("state").as(String.class), label.getState());//where labelname like "小明"
                    list.add(predicate);
                }
                Predicate[] pre = new Predicate[list.size()];
                list.toArray(pre);
                return cb.and(pre);
            }
        },pageable);
    }
③ 在API中进行测试
页码:1
size:2
{
  "labelname": "H"
}
#测试结果:
{
  "flag": true,
  "code": 20000,
  "message": "查询成功",
  "data": {
    "total": 2,
    "rows": [
      {
        "id": "1098215421804314624",
        "labelname": "PHP",
        "state": "2",
        "count": 0,
        "fans": null,
        "recommend": "1"
      },
      {
        "id": "1098227211468578816",
        "labelname": "PYTHON",
        "state": "2",
        "count": 0,
        "fans": null,
        "recommend": "1"
      }
    ]
  }
}

3)、招聘微服务

3.1)、热门企业列表

需求分析:查询企业表ishot字段为1的记录 【代码较为简单,三层如下】

controller层:
    @GetMapping("/search/hotlist")
    public Result findHotEnterprise(){
        return new Result(true,StatusCode.OK,"查询成功",enterpriseService.findHotEnterprise());
    }

service层:
    /**
     * 查询热门企业
     */
    public List<Enterprise> findHotEnterprise(){
        return enterpriseDao.findAllByIshot("1");
    }

dao层:
  public List<Enterprise> findAllByIshot(String ishot);

//省略测试部分

3.2)、推荐职位列表

需求分析:查询状态为2并以创建日期降序排序,查询前4条记录

//基础代码:三和一
dao层:
    /**
     * 热门职位:查询状态码为2 的
     */
    public List<Recruit> findTop6ByStateOrderByCreatetime(String state);
    //where state= ? order by creatime

service层:
    /**
     * 查询热门职位
     */
    public List<Recruit> hotJob(){
        return recruitDao.findTop6ByStateOrderByCreatetime("2");
    }

controller:
    /**
     * 查询热门职位
     */
    @GetMapping("/search/recommend")
    public Result hotJob(){
        return new Result(true,StatusCode.OK,"查询成功",recruitService.hotJob());
    }

3.3)、最新职位列表

需求分析:查询状态不为0并以创建日期降序排序,查询前12条记录

//基础代码,三合一:
dao层:
    /**
     * 最新职位:
     * 查询状态码不为0 的  按照日期排序
     */
    public List<Recruit> findTop6ByStateNotOrderByCreatetime(String state);
    //where state != ? order by creatime

service层:
    /**
     * 查询最新职位
     */
    public List<Recruit> newJob(){
        return recruitDao.findTop6ByStateNotOrderByCreatetime("0");
    }

controller层:
    /**
     * 查询最新职位
     */
    @GetMapping("/search/newlist")
    public Result newJob(){
        return new Result(true,StatusCode.OK,"查询成功",recruitService.newJob());
    }

4)、问答微服务

4.1)、最新回答列表

4.2)、热门回答列表

4.3)、等待回答列表

dao层:注意返回对象是Page

    /**
     * 最新回答
     */

    @Query(value = "SELECT * FROM tb_problem,tb_pl WHERE id = labelid AND labelid=? ORDER BY replytime DESC",nativeQuery = true)
    public Page<Problem> newList(String labelid, Pageable pageable);

    /**
     * 热门回答
     */
    @Query(value = "SELECT * FROM tb_problem,tb_pl WHERE id = labelid AND labelid=? ORDER BY reply DESC",nativeQuery = true)
    public Page<Problem> hotList(String labelid, Pageable pageable);

    /**
     * 等待回答
     */
    @Query(value = "SELECT * FROM tb_problem,tb_pl WHERE id = labelid AND labelid=?  AND reply=0 ORDER BY createtime DESC",nativeQuery = true)
    public Page<Problem> waitList(String labelid, Pageable pageable);
service层:
    public Page<Problem> newList(String labelid, Integer page,Integer size){
        Pageable pageable = PageRequest.of(page-1,size);
        return problemDao.newList(labelid,pageable);
    }

    public Page<Problem> hotList(String labelid, Integer page,Integer size){
        Pageable pageable = PageRequest.of(page-1,size);
        return problemDao.hotList(labelid,pageable);
    }
    public Page<Problem> waitList(String labelid, Integer page,Integer size){
        Pageable pageable = PageRequest.of(page-1,size);
        return problemDao.waitList(labelid,pageable);
    }
controller层:
    @GetMapping("/newlist/{label}/{page}/{size}")
    public Result newList( @PathVariable String label,@PathVariable Integer page,@PathVariable Integer size){
        Page<Problem> newList = problemService.newList(label, page, size);
        return new Result(true,StatusCode.OK,"查询成功",newList);

    }

    @GetMapping("/hotlist/{label}/{page}/{size}")
    public Result hotList(@PathVariable String label,@PathVariable Integer page,@PathVariable Integer size){
        Page<Problem> hotList = problemService.hotList(label, page, size);
        return new Result(true,StatusCode.OK,"查询成功",hotList);
    }

    @GetMapping("/waitlist/{label}/{page}/{size}")
    public Result waitList(@PathVariable String label,@PathVariable Integer page, @PathVariable Integer size){

        Page<Problem> waitList = problemService.waitList(label, page, size);
        return  new Result(true,StatusCode.OK,"查询成功",waitList);
    }

5)、文章微服务

5.1)、审核功能实现

5.2)、点赞功能实现

dao层:
    //修改表的内容,注意在方法前加上Modifying注解
    @Modifying
    @Query(value = "UPDATE `tb_article` SET state=1 WHERE id = ?",nativeQuery = true)
    public void updateState(String id);

    @Modifying
    @Query(value = "UPDATE `tb_article` SET thumbup=thumbup+1 WHERE id = ?",nativeQuery = true)
    public void thumbUp(String id);
service层:
   //注意事务的控制。加上Transactional注解
   public void updateState(String id){
        articleDao.updateState(id);
    }

    public void thumbUp(String id){
        articleDao.thumbUp(id);
    }

6)、缓存的处理

6.1)、使用Redis实现

① 开启一个Redis容器
docker run -di --name=tensquare_redis -p 6379:6379 redis
②导入依赖
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
③service层代码实现

    @Autowired
    private RedisTemplate redisTemplate;

    //查询:第一次查到null,放进缓存,以后从缓存中取得
    public Article findById(String id) {
        Article article = (Article) redisTemplate.opsForValue().get("article_" + id);
        if (article==null){
            article = articleDao.findById(id).get();
            redisTemplate.opsForValue().set("article_"+id,article);
        }
        return article ;
    }

    /**
     * 修改:将原有的缓存删除
     * @param article
     */
    public void update(Article article) {
        redisTemplate.delete("article_"+article.getId());
        articleDao.save(article);
    }

    /**
     * 删除:将原有的缓存删除
     * @param id
     */
    public void deleteById(String id) {
        redisTemplate.delete("article_"+id);
        articleDao.deleteById(id);
    }
④Redis设置过期时间
redisTemplate.opsForValue().set("article_"+id,article,10, TimeUnit.DAYS);

6.2)、使用Spring Cache实现

在活动微服务中实现

①开启缓存机制
//在application上添加注解:表示开启缓存
@EnableCaching
public class GatheringApplication {

    public static void main(String[] args) {
        SpringApplication.run(GatheringApplication.class, args);
    }
②在service层中的方法上添加注解使用缓存
    //添加缓存
    @Cacheable(value = "gathering",key = "#id")
    public Gathering findById(String id) {
        return gatheringDao.findById(id).get();
    }

    //删除缓存
    @CacheEvict(value = "gathering",key = "#gathering.id")
    public void update(Gathering gathering) {
        gatheringDao.save(gathering);
    }

day02 : JPA的基本使用和多种缓存技术对比的更多相关文章

  1. Android ImageCache图片缓存,使用简单,支持预取,支持多种缓存算法,支持不同网络类型,扩展性强

    本文主要介绍一个支持图片自动预取.支持多种缓存算法的图片缓存的使用及功能.图片较大需要SD卡保存情况推荐使用ImageSDCardCache. 与Android LruCache相比主要特性:(1). ...

  2. 在.NET项目中使用PostSharp,使用CacheManager实现多种缓存框架的处理

    在前面几篇随笔中,介绍了PostSharp的使用,以及整合MemoryCache,<在.NET项目中使用PostSharp,实现AOP面向切面编程处理>.<在.NET项目中使用Pos ...

  3. 【Java/Android性能优 6】Android 图片SD卡缓存 使用简单 支持预取 支持多种缓存算法 支持不同网络类型 支持序列化

    本文转自:http://www.trinea.cn/android/android-imagesdcardcache/ 本文主要介绍一个支持图片自动预取.支持多种缓存算法.支持数据保存和恢复的图片Sd ...

  4. 【Java/Android性能优5】 Android ImageCache图片缓存,使用简单,支持预取,支持多种缓存算法,支持不同网络类型,扩展性强

    本文转自:http://www.trinea.cn/android/android-imagecache/ 主要介绍一个支持图片自动预取.支持多种缓存算法.支持二级缓存.支持数据保存和恢复的图片缓存的 ...

  5. 【Java/Android性能优 4】PreloadDataCache支持预取的数据缓存,使用简单,支持多种缓存算法,支持不同网络类型,扩展性强

    本文转自:http://www.trinea.cn/android/preloaddatacache/ 本文主要介绍一个支持自动向前或向后获取新数据的缓存的使用及功能.Android图片内存缓存可见I ...

  6. PHP缓存技术的多种方法小结

    这里所说的数据缓存是指数据库查询PHP缓存机制,每次访问页面的时候,都会先检测相应的缓存数据是否存在,如果不存在,就连接数据库,得到数据,并把查询结果序列化后保存到文件中,以后同样的查询结果就直接从缓 ...

  7. 总结PHP缓存技术的多种方法

    这里所说的数据缓存是指数据库查询PHP缓存机制,每次访问页面的时候,都会先检测相应的缓存数据是否存在,如果不存在,就连接数据库,得到数据,并把查询结果序列化后保存到文件中,以后同样的查询结果就直接从缓 ...

  8. 网站缓存技术总结( ehcache、memcache、redis对比)

    网站技术高速发展的今天,缓存技术已经成为大型网站的一个关键技术,缓存设计好坏直接关系的一个网站访问的速度,以及购置服务器的数量,甚至影响到用户的体验. 网站缓存按照存放的地点不同,可以分为客户端缓存. ...

  9. ASP.NET Core 缓存技术 及 Nginx 缓存配置

    前言 在Asp.Net Core Nginx部署一文中,主要是讲述的如何利用Nginx来实现应用程序的部署,使用Nginx来部署主要有两大好处,第一是利用Nginx的负载均衡功能,第二是使用Nginx ...

随机推荐

  1. BZOJ 4195: [Noi2015]程序自动分析 并查集+离散化

    LUOGU 1955BZOJ 4195 题目描述 在实现程序自动分析的过程中,常常需要判定一些约束条件是否能被同时满足. 考虑一个约束满足问题的简化版本:假设x1,x2,x3...代表程序中出现的变量 ...

  2. FL Studio中音频ASIO4ALL的设置

    上期我们讲解了FL Studio中音频的相关设置,今天我们来进一步讲解音频设置中的ASIO4ALL的设置,FL Studio安装包括FL Studio ASIO和第三方ASIO驱动程序ASIO4ALL ...

  3. 软件测试4gkd

    一.性能测试有几种类型,它们之间什么关系? (1)性能测试包括:负载测试.压力测试.配置测试.并发测试.容量测试.可靠性测试.失败测试. 负载测试:通过逐渐增加系统的负载,测试系统性能的变化,并最终确 ...

  4. hdfs性能调优(cloudera)

    参照官方文档:http://www.cloudera.com/content/cloudera/en/documentation/core/latest/topics/cdh_ig_yarn_tuni ...

  5. Educational Codeforces Round 48 (Rated for Div. 2)

    http://codeforces.com/contest/1016 A. 没想到这个也会TLE,太粗心了 B. 暴力就好了,多情况讨论又出错... 思路跟我一样的解法   为什么我做了那么多讨论,原 ...

  6. [译]RabbitMQ教程C#版 - 路由

    先决条件 本教程假定 RabbitMQ 已经安装,并运行在localhost标准端口(5672).如果你使用不同的主机.端口或证书,则需要调整连接设置. 从哪里获得帮助 如果您在阅读本教程时遇到困难, ...

  7. npm版本安装问题

    问题一 描述 运行npm install之后,前端页面console控制台报错,invalid props. 排查 1. 排除了代码问题,完全一样的代码,其他人的运行无误. 2.猜想可能是版本号问题, ...

  8. 使用win10的开始屏幕,在系统中设置简洁、快捷桌面

    前几天入手了一个本本,由于之前电脑使用的柠檬桌面软件和现在本本的分辨率不适应,意外发现win10自带的开始屏幕整理桌面也是很有意思,再加上触摸板的手势,瞬间觉得整个电脑都清洁许多.废话少说,开始上料. ...

  9. idea Debug快捷键

    快捷键 介绍 F7 在 Debug 模式下,进入下一步,如果当前行断点是一个方法,则进入当前方法体内, 如果该方法体还有方法,则不会进入该内嵌的方法中 * F8 在 Debug 模式下,进入下一步,如 ...

  10. 注入(injector)

    在java开发中有时候我们的一个类需要依赖另外一个类,这种就是依赖关系,创建对象的工作一般由spring容器来完成然后注入给调用者,这种就是依赖注入. Java依赖注入设计原则允许我们移除硬编码依赖和 ...