项目2---十次方项目开发---后台--查询与缓存---02

-------------------------------------------------------------------01------------------------------------------------------------------------

springdataJpa:jpa的操作。

标签查询。

写service:

service怎么写呢:分页 条件 分页和条件。

service的书写:

 public List<Label> findSearch(Label label) {
        Specification<Label> specification=new Specification<Label>() {
            /**
             *
             * @param root 根对象,也就是要把条件封装到哪个对象中,where leiming=label.getId
             * @param query 封装的是查询关键字, 比如group by order by等
             * @param cb 用来封装条件对象
             * @return
             */
            @Override
            public Predicate toPredicate(Root<Label> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                //new一个集合存放所有的条件
                List<Predicate> list=new ArrayList<Predicate>();
                if(label.getLabelname()!=null &&!"".equals(label.getLabelname())){
                    Expression<String> labelname = root.get("labelname").as(String.class);
                    Predicate predicate = cb.like(labelname, "%" + label.getLabelname() + "%");//where labelname like "%XX%"
                    list.add(predicate);
                }
                if(label.getState()!=null && !"".equals(label.getState())){
                    Expression<String> state = root.get("state").as(String.class);
                    Predicate predicate = cb.equal(state,label.getState());//where labeState = "XX"
                    list.add(predicate);
                }
                //new一个数组作为最终返回值的条件
                Predicate[] parr = new Predicate[list.size()];
                //把list直接转成数组
                parr = list.toArray(parr);
                return cb.and(parr);
            }
        };
        List<Label> labels = labelDao.findAll(specification);
        return  labels;

    }

测试:

JSON:

{
  "labelname": "string123",
  "state": "1",
  "count": 0,
  "recommend": "1"
}

------------------------------------------------------------------------02----------------------------------------------------------------------------------------

分页的:

写controller:

 /**
     * 标签条件查询
     * @return
     */
    @RequestMapping(value="/search/{page}/{size}",method=RequestMethod.POST)
    public Result PageQuery(@PathVariable("page")Integer page,@PathVariable("size")Integer size,@RequestBody Label label){
        Page<Label> pageData=labelService.PageQuery(label,page,size);
        return new Result(true,StatusCode.OK,"查询成功",new PageResult<Label>(pageData.getTotalElements(),pageData.getContent()));
    }

写service,这个是固定的写法。

   public Page<Label> PageQuery(Label label, Integer page, Integer size) {
        Specification<Label> specification = new Specification<Label>() {
            /**
             *
             * @param root 根对象,也就是要把条件封装到哪个对象中,where leiming=label.getId
             * @param query 封装的是查询关键字, 比如group by order by等
             * @param cb 用来封装条件对象
             * @return
             */
            @Override
            public Predicate toPredicate(Root<Label> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                //new一个集合存放所有的条件
                List<Predicate> list = new ArrayList<Predicate>();
                if (label.getLabelname() != null && !"".equals(label.getLabelname())) {
                    Expression<String> labelname = root.get("labelname").as(String.class);
                    Predicate predicate = cb.like(labelname, "%" + label.getLabelname() + "%");//where labelname like "%XX%"
                    list.add(predicate);
                }
                if (label.getState() != null && !"".equals(label.getState())) {
                    Expression<String> state = root.get("state").as(String.class);
                    Predicate predicate = cb.equal(state, label.getState());//where labelname like "%XX%"
                    list.add(predicate);
                }
                //new一个数组作为最终返回值的条件
                Predicate[] parr = new Predicate[list.size()];
                //把list直接转成数组
                parr = list.toArray(parr);
                return cb.and(parr);
            }
        };
        Pageable pageable = PageRequest.of(page - 1, size);
        return labelDao.findAll(specification, pageable);
    }

注意这个page是从1开始的。要减1变为0。

查询:

结果:

------------------------------------------------------------------03------------------------------------------------------------------------

招聘微服务:

用代码生成器生成代码:

第一步:

第二步:

第三步:

写pom:

修改父工程的信息。

第四步:

修改启动类的名称

修改yml文件。

-------------------------------------------------------------------04------------------------------------------------------------------------

做这个界面。

写面向对象的sql语句,不能出现表名。不推荐这样写的。

-------------------------------------------------------------------05------------------------------------------------------------------------

查询热门企业:

写相关的service和controller

查询:

http://localhost:9002/enterprise/search/hotlist

-------------------------------------------------------------------06------------------------------------------------------------------------

带顺序的查询。

第一步:

第二步:

写service和controller

测试:

http://localhost:9002/recruit/search/newlist
http://localhost:9002/recruit/search/recommend

-------------------------------------------------------------------07------------------------------------------------------------------------

问答的微服务:

问答微服务的业务代码生成。

我们要写sql语句了。

第一步:代码生成器tensquare_qa,代码生成器framework。

第二步:改代码

-------------------------------------------------------------------08------------------------------------------------------------------------

php的最新热门等待

java的最新热门等待

要关联表。

联合主键表示联合是唯一的。问题可能有很多标签,标签可能含有很多问题。

联合查询必须写sql语句了。

---------------------------------------------------------------------------09---------------------------------------------------------------------------------

JPA的联合查询。最新 热门 等待

第一步:

写sql:写Dao。

 @Query(value = "select * from tb_problem,tb_pl where id = problemid and labelid=? order by replytime DESC " ,nativeQuery = true)
    Page<Problem> newList(String labelid, Pageable pageable);

    @Query(value = "select * from tb_problem,tb_pl where id = problemid and labelid=? order by reply DESC " ,nativeQuery = true)
    Page<Problem> hotList(String labelid,Pageable pageable);

    @Query(value = "select * from tb_problem,tb_pl where id = problemid and labelid=? and reply=0 order by createtime DESC " ,nativeQuery = true)
    Page<Problem> waitList(String labelid, Pageable pageable);

JPA的分页就这么简单。

想分页传参数就可以。

写service和controller。

测试:

http://localhost:9003/problem/newlist/1/1/1

单表查询很少。

-------------------------------------------------------------------------------10-------------------------------------------------------------------------------------

文章模块编写:

表结构:审核才能显示出来,没审核是不让显示的。

第一步:写dao

/**
     * 增删改需要加@Modifyting
     * 审核文章
     */
    @Modifying
    @Query(value = "update tb_article set state=1 where id =? ",nativeQuery = true)
    void updateState(String id);

    /**
     * 点赞数增加
     * @param id
     */
    @Modifying
    @Query(value = "update tb_article set thumbup = thumbup + 1 where id =? ",nativeQuery = true)
    void addThumbup(String id);

注意一下:注意增删改都要加一个@Modifying,线程问题都要加。

第二步:写service和controller

测试:

http://localhost:9004/article/thumbup/1

-------------------------------------------------------------------11----------12--------------------------------------------------------------

SpringDataRedis

制作redis容器:一直查数据库使数据库的压力过大。

启动redist:

docker run -di --name=tensquare_redis -p 6379:6379 redis

-------------------------------------------------------------------13------------------------------------------------------------------------

使用redis:

第一步:pom

  <dependency>
		  <groupId>org.springframework.boot</groupId>
		  <artifactId>spring-boot-starter-data-redis</artifactId>
	  </dependency>

第二步:yml文件

 redis:
     host: 192.168.244.136

第三步:写一个查询下。先在缓存中查询,要是缓存没有的话就在数据库查询下,更新缓存。

	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;
	}

扩展:

stringRedisTemplate.opsForValue().set("test", "100",60*10,TimeUnit.SECONDS);//向redis里存入数据和设置缓存过期时间
stringRedisTemplate.opsForValue().get("test")//根据key获取缓存中的val
stringRedisTemplate.boundValueOps("test").increment(-1);//val做-1操作
stringRedisTemplate.boundValueOps("test").increment(1);//val +1
stringRedisTemplate.getExpire("test")//根据key获取过期时间
stringRedisTemplate.getExpire("test",TimeUnit.SECONDS)//根据key获取过期时间并换算成指定单位
stringRedisTemplate.delete("test");//根据key删除缓存
stringRedisTemplate.hasKey("546545");//检查key是否存在,返回boolean值
stringRedisTemplate.expire("red_123",1000 , TimeUnit.MILLISECONDS);//设置过期时间
stringRedisTemplate.opsForSet().add("red_123", "1","2","3");//向指定key中存放set集合
stringRedisTemplate.opsForSet().isMember("red_123", "1")//根据key查看集合中是否存在指定数据
stringRedisTemplate.opsForSet().members("red_123");//根据key获取set集合

-------------------------------------------------------------------14-------------------------------------------------------------------------

修改和删除要更新或者删除缓存的。

	/**
	 * 修改
	 * @param article
	 */
	public void update(Article article)
    {
        redisTemplate.opsForValue().set("article_"+article.getId(),article);
		articleDao.save(article);
	}

	/**
	 * 删除
	 * @param id
	 */
	public void deleteById(String id) {
        redisTemplate.delete("article_"+id);
	    articleDao.deleteById(id);
	}

-------------------------------------------------------------------15------------------------------------------------------------------------

redis过期时间:

注册,验证码的过期时间。

	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,10,TimeUnit.SECONDS);
        }
        return article;
	}

-------------------------------------------------------------------------------16---------------------------------------------------------------------------------------

springcache:

没有过期时间使sringcache。

------------------------------------------------------------------------------17------------------------------------------------------------------------------------

在活动的模块用springcache。

第一步:

第二步:

gathering是CacheManager的名字,id是cache的键值对。

@Cacheable(value="gathering",key="#id")
	public Gathering findById(String id) {
		return gatheringDao.findById(id).get();
	}

第三步:

/**
	 * 修改
	 * @param gathering
	 */
	@CacheEvict(value="gathering",key="#gathering.id")
	public void update(Gathering gathering) {
		gatheringDao.save(gathering);
	}
	/**
	 * 删除
	 * @param id
	 */
	@CacheEvict(value="gathering",key="#id")
	public void deleteById(String id) {
		gatheringDao.deleteById(id);
	}

弊端不能设置过期时间。

-------------------------------------------------------------------18------------------------------------------------------------------------

发布了308 篇原创文章 · 获赞 11 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_28764557/article/details/104081712