day02 : JPA的基本使用和多种缓存技术对比
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的基本使用和多种缓存技术对比的更多相关文章
- Android ImageCache图片缓存,使用简单,支持预取,支持多种缓存算法,支持不同网络类型,扩展性强
本文主要介绍一个支持图片自动预取.支持多种缓存算法的图片缓存的使用及功能.图片较大需要SD卡保存情况推荐使用ImageSDCardCache. 与Android LruCache相比主要特性:(1). ...
- 在.NET项目中使用PostSharp,使用CacheManager实现多种缓存框架的处理
在前面几篇随笔中,介绍了PostSharp的使用,以及整合MemoryCache,<在.NET项目中使用PostSharp,实现AOP面向切面编程处理>.<在.NET项目中使用Pos ...
- 【Java/Android性能优 6】Android 图片SD卡缓存 使用简单 支持预取 支持多种缓存算法 支持不同网络类型 支持序列化
本文转自:http://www.trinea.cn/android/android-imagesdcardcache/ 本文主要介绍一个支持图片自动预取.支持多种缓存算法.支持数据保存和恢复的图片Sd ...
- 【Java/Android性能优5】 Android ImageCache图片缓存,使用简单,支持预取,支持多种缓存算法,支持不同网络类型,扩展性强
本文转自:http://www.trinea.cn/android/android-imagecache/ 主要介绍一个支持图片自动预取.支持多种缓存算法.支持二级缓存.支持数据保存和恢复的图片缓存的 ...
- 【Java/Android性能优 4】PreloadDataCache支持预取的数据缓存,使用简单,支持多种缓存算法,支持不同网络类型,扩展性强
本文转自:http://www.trinea.cn/android/preloaddatacache/ 本文主要介绍一个支持自动向前或向后获取新数据的缓存的使用及功能.Android图片内存缓存可见I ...
- PHP缓存技术的多种方法小结
这里所说的数据缓存是指数据库查询PHP缓存机制,每次访问页面的时候,都会先检测相应的缓存数据是否存在,如果不存在,就连接数据库,得到数据,并把查询结果序列化后保存到文件中,以后同样的查询结果就直接从缓 ...
- 总结PHP缓存技术的多种方法
这里所说的数据缓存是指数据库查询PHP缓存机制,每次访问页面的时候,都会先检测相应的缓存数据是否存在,如果不存在,就连接数据库,得到数据,并把查询结果序列化后保存到文件中,以后同样的查询结果就直接从缓 ...
- 网站缓存技术总结( ehcache、memcache、redis对比)
网站技术高速发展的今天,缓存技术已经成为大型网站的一个关键技术,缓存设计好坏直接关系的一个网站访问的速度,以及购置服务器的数量,甚至影响到用户的体验. 网站缓存按照存放的地点不同,可以分为客户端缓存. ...
- ASP.NET Core 缓存技术 及 Nginx 缓存配置
前言 在Asp.Net Core Nginx部署一文中,主要是讲述的如何利用Nginx来实现应用程序的部署,使用Nginx来部署主要有两大好处,第一是利用Nginx的负载均衡功能,第二是使用Nginx ...
随机推荐
- CH 5102Mobile Service题解
题目: 用动态规划很容易将完成任务量作为dp的阶段,通过指派服务员,从当前i-1个任务转移到i个任务: 我们可以用一个四维数组f[i][x][y][z]来表示在完成当前任务i时,三个机器人分别在x,y ...
- 《Java程序设计》课程实验要求
目录 <Java程序设计>课程实验要求 注册实验楼账号 实验一 Java开发环境的熟悉 实验二<Java面向对象程序设计> 实验三 <敏捷开发与XP实践> 实验四 ...
- SpringIOC的概念理解、构造器注入、setter注入、p命名空间注入、IOC容器介绍与比较
1.IOC概念理解 IOC(Inversion of Control)即“控制反转”,不是什么技术,而是一种设计思想.在Java开发中,Ioc意味着将你设计好的对象交给容器控制,而不是传统的在你的对象 ...
- 从事三年java开发后, 我打算转人工智能
作为一个2015年参加java培训,2016年计算机科学与技术本科毕业后一直从事java开发的程序员来说, 做出这一步真的不容易, 可是我没赶上java最火的时候,反而渐渐感受到了java的没落, 目 ...
- MySQL单表多次查询和多表联合查询,哪个效率高?
很多高性能的应用都会对关联查询进行分解. 简单地,可以对每个表进行一次单表查询,然后将结果在应用程序中进行关联.例如,下面这个查询: select * from tag join tag_post o ...
- Vue-admin工作整理(十三):Vuex-严格模式
严格模式:开发过程中对规范的要求,定义方式为在store实例初始化的时候将strict设置为true,这样的话就是开启了严格模式.在这种情况下,如果要直接修改state里面的值,那就会报问题.那么也可 ...
- Ant Design of React 框架使用总结1
一. 为什么要用UI 框架 统一了样式交互动画 . Ui框架会对样式,交互动画进行统一,保证了系统风格完整统一,不像拼凑起来的. 兼容性 ,不是去兼容IE 6 7 8那些低版本浏览器,而是对主流的标 ...
- leecode第二百三十七题(删除链表中的节点)
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode ...
- HBase详解
1. hbase简介 1.1. 什么是hbase HBASE是一个高可靠性.高性能.面向列.可伸缩的分布式存储系统,利用HBASE技术可在廉价PC Server上搭建起大规模结构化存储集群. H ...
- 规则引擎 drools
https://www.jianshu.com/p/725811f420db 深入了解Drools 简单介绍 笔者正在做风控系统,风控系统里边存在非常多的规则(比如:age < 16 || ag ...