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 ...
随机推荐
- HTML与CSS的一些知识(一)
一般写代码的时候,总会有些小错误.为了便于修改以及查找,所以代码格式要写规范,而且一定一定要写注释.因为有时候代码写得多了,真的连自己都找不到自己要找的东西在哪里.还有命名也要见名知意. 再说一些HT ...
- Markdown介绍
如何使用.md文件 本文档为Markdown格式,建议利用Visual Studio Code+ Markdown All in One插件修改.参考链接:基础mdbasic,高级mdextended
- 原生JS实现轮播效果
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...
- mac 开启ntfs 权限
原文: https://zhuanlan.zhihu.com/p/29542892 参考: https://bbs.feng.com/read-htm-tid-9932031.html 其实最早在OS ...
- js ++i和i++的区别
++i和i++的定义: 1. 如果用前缀运算符对一个变量增1(减1),则在将该变量增1(减1)后,用新值在表达式中进行其他的运算. 2. 如果用后缀运算符对一个变量增1(减1),则用该变量的原 ...
- 【转】RTP学习笔记
转自:https://www.cnblogs.com/yoyotl/p/5650101.html 一.定义 实时传输协议(Real- time Transport Protocol,RTP)是在Int ...
- YARN的三种调度器的使用
YRAN提供了三种调度策略 一.FIFO-先进先出调度器 YRAN默认情况下使用的是该调度器,即所有的应用程序都是按照提交的顺序来执行的,这些应用程序都放在一个队列中,只有在前面的一个任务执行完成之后 ...
- Mock.js常用占位符——Basic、Date、Color
1. Basic 在通过占位符引用方法时, Mock.mock('@boolean') : Mock.mock('@boolean()') 都可以调用方法 方法 含义 使用举例 Random.bo ...
- java中JScrollPane不显示水平滚动条的解决办法
在JPanel中添加了表格,表格中对东西太多,需要水平滚动条滑动才能够完全找到所有数据,如果没有水平滚动条的话,数据堆积在一起,无法分开 做法是: 第一步:先将表格自动调整的状态给关闭掉:table. ...
- Azure中block和Page的比较 Azure: Did You Know? Block vs Page Blobs
Azure storage service supports two types of blobs (blob, or BLOB, stand for Binary Large OBject, i.e ...