Java jpa外连接查询join案例详解

网友投稿 244 2022-12-11

Java jpa外连接查询join案例详解

1、IndexTagController.java

@GetMapping("/tags/{id}")

public String types(@PageableDefault(size = 3,sort = {"updateTime"},direction = Sort.Direction.DESC)Pageable pageable,

@PathVariable long id,

Model model,

HttpSession session){

//找到所有的标签,并且按照标签新闻量排序

List tags = tagService.listTagTop(50);

if(id == -1){

//得nDFZzwdQww到最大数据量的分类

id = tags.get(0).getId();

}

model.addAttribute("tags",tags);

model.addAttribute("page",newsService.listNews(id,pageable));

model.addAttribute("activeId",id);

session.setAttribute("query","");

return "tags";

}

newService.listNews(id,pgeable)中id为标签的id,这个方法要做的就是查询出标签中包含id为参数id的所有新闻。

2、业务层代码

NewService.java是一个接口,其中存在以下方法

//根据标签Id查找符合条件的新闻

Page listNews(long id,Pageable pageable);

NewServiceImpl.java为实现NewService接口的类,实现listNews方法

@Override

public Page listNews(long id, Pageable pageable) {

return newsRepository.findAll(new Specification() {

@Override

public Predicate toPredicate(Root root, CriteriaQuery cq, CriteriaBuilder cb) {

//外连接查询 Join

Join join =rootnDFZzwdQww.join("tags");

return cb.equal(join.get("id"),id);

}

},pageable);

}

NewsRepository.java 继承了JpaSpecificationExecutor

public interface NewsRepository extends JpaRepository, JpaSpecificationExecutor {

@Query("select n from News n where n.recommend = true ")

List findTop(Pageable pageable);

@Query("select n from News n where n.title like ?1 or n.content like ?1")

Page findByQuery(String query,Pageable pageable);

@Query("select function('date_format',n.updateTime,'%Y') as year1 from News n group by year1 order by year1 desc ")

List findGroupYear();

@Query("select n from News n where function('date_format',n.updateTime,'%Y') = ?1 ")

List findByYear(String year);

}

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:深入理解Java SpringCloud Ribbon 负载均衡
下一篇:java Zookeeper简述
相关文章

 发表评论

暂时没有评论,来抢沙发吧~