Spring Data JPA 實現多表關聯查詢
最近抽出時間來做部落格,資料庫操作使用的是 JPA,相對比 Mybatis 而言,JPA 單表操作非常方便,增刪改查都已經寫好了。但是多表操作就不如 Mybatis 那種直接寫 sql 語句來得方便,JPA 的多表操作比較麻煩。
需求描述
獲得文章列表,文章列表裡需要顯示每篇文章的分類目錄列表,因為一個文章可能有多個分類,一個分類當然也可以對應多篇文章的。
下面是我用截圖軟體畫的一個圖,描述的是三張表和其主要欄位。
文章表 article 和分類表 category 通過 中間表 article_category 關聯
我們的需求也很簡單,從資料庫裡查詢所有文章,並給每篇文章加一個分類列表的屬性。
如影像這樣
程式碼實現
Spring Data JPA 需要的依賴和配置檔案這裡就不給出了,因為不是本文的重點。
實體類
1、實體類 Article.java
- package com.liuyanzhao.blog.entity;
- import javax.persistence.*;
- import java.io.Serializable;
- import java.util.Date;
- import java.util.Set;
- /**
- * @author 言曌
- * @date 2017/12/11 下午7:46
- */
- @Entity
- @Table(name = "article")
- public class Article implements Serializable {
- private static final long serialVersionUID = 7419229779731522702L;
- @Id
- @GeneratedValue(strategy = GenerationType.IDENTITY)
- private Integer id;
- @Lob//text
- @Column(columnDefinition="text")
- private String title;
- @Lob //longtext
- @Column(columnDefinition="longtext")
- private String content;
- private Integer userId;
- private Integer likeCount;
- private Date createTime;
- private Date updateTime;
- private Integer status;
- @OneToMany(mappedBy = "article",cascade = CascadeType.ALL, orphanRemoval = true)
- private Set<ArticleCategory> articleCategoryList;
- public Integer getId() {
- return id;
- }
- public void setId(Integer id) {
- this.id = id;
- }
- public String getTitle() {
- return title;
- }
- public void setTitle(String title) {
- this.title = title;
- }
- public String getContent() {
- return content;
- }
- public void setContent(String content) {
- this.content = content;
- }
- public Integer getUserId() {
- return userId;
- }
- public void setUserId(Integer userId) {
- this.userId = userId;
- }
- public Integer getLikeCount() {
- return likeCount;
- }
- public void setLikeCount(Integer likeCount) {
- this.likeCount = likeCount;
- }
- public Date getCreateTime() {
- return createTime;
- }
- public void setCreateTime(Date createTime) {
- this.createTime = createTime;
- }
- public Date getUpdateTime() {
- return updateTime;
- }
- public void setUpdateTime(Date updateTime) {
- this.updateTime = updateTime;
- }
- public Integer getStatus() {
- return status;
- }
- public void setStatus(Integer status) {
- this.status = status;
- }
- public static long getSerialVersionUID() {
- return serialVersionUID;
- }
- public Set<ArticleCategory> getArticleCategoryList() {
- return articleCategoryList;
- }
- public void setArticleCategoryList(Set<ArticleCategory> articleCategoryList) {
- this.articleCategoryList = articleCategoryList;
- }
- }
注意 43-44 行
2、實體類 Category.java
- package com.liuyanzhao.blog.entity;
- import javax.persistence.*;
- import java.io.Serializable;
- import java.util.Set;
- /**
- * @author 言曌
- * @date 2017/12/11 下午8:16
- */
- @Entity
- @Table(name = "category")
- public class Category implements Serializable {
- private static final long serialVersionUID = 7419229779731522702L;
- @Id
- @GeneratedValue(strategy = GenerationType.IDENTITY)
- private Integer id;
- private String name;
- private String key;
- private Integer status;
- @OneToMany(mappedBy = "category")
- private Set<ArticleCategory> articleCategoryList;
- public Integer getId() {
- return id;
- }
- public void setId(Integer id) {
- this.id = id;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public Integer getStatus() {
- return status;
- }
- public void setStatus(Integer status) {
- this.status = status;
- }
- public String getKey() {
- return key;
- }
- public void setKey(String key) {
- this.key = key;
- }
- public static long getSerialVersionUID() {
- return serialVersionUID;
- }
- public Set<ArticleCategory> getArticleCategoryList() {
- return articleCategoryList;
- }
- public void setArticleCategoryList(Set<ArticleCategory> articleCategoryList) {
- this.articleCategoryList = articleCategoryList;
- }
- }
注意 28-29 行
3、實體類 ArticleCategory.java
- package com.liuyanzhao.blog.entity;
- import javax.persistence.*;
- import java.io.Serializable;
- /**
- * @author 言曌
- * @date 2017/12/12 下午4:08
- */
- @Entity
- @Table(name = "article_category")
- public class ArticleCategory implements Serializable {
- private static final long serialVersionUID = 7419229779731522702L;
- @Id
- @ManyToOne
- @JoinColumn(name = "article_id")
- private Article article;
- @Id
- @ManyToOne
- @JoinColumn(name = "category_id")
- private Category category;
- public static long getSerialVersionUID() {
- return serialVersionUID;
- }
- public Article getArticle() {
- return article;
- }
- public void setArticle(Article article) {
- this.article = article;
- }
- public Category getCategory() {
- return category;
- }
- public void setCategory(Category category) {
- this.category = category;
- }
- }
注意 17-25 行
Dao 層
1、ArticleDao.java
- package com.liuyanzhao.blog.dao;
- import com.liuyanzhao.blog.entity.Article;
- import com.liuyanzhao.blog.vo.ArticleVO;
- import org.springframework.data.domain.Page;
- import org.springframework.data.domain.Pageable;
- import org.springframework.data.jpa.repository.JpaRepository;
- /**
- * @author 言曌
- * @date 2017/11/28 下午3:31
- */
- public interface ArticleDao extends JpaRepository<Article, Integer> {
- //獲取文章列表,按status和id降序
- Page<ArticleVO> findAllByOrderByStatusDescIdDesc(Pageable pageable);
- }
2、CategoryDao.java
- package com.liuyanzhao.blog.dao;
- import com.liuyanzhao.blog.entity.Category;
- import org.springframework.data.jpa.repository.JpaRepository;
- /**
- * @author 言曌
- * @date 2017/12/12 上午11:16
- */
- public interface CategoryDao extends JpaRepository<Category, Integer> {
- }
Service 層
1、ArticleService.java
- package com.liuyanzhao.blog.service;
- import com.liuyanzhao.blog.vo.ArticleVO;
- import org.springframework.data.domain.Page;
- import org.springframework.data.domain.Pageable;
- /**
- * @author 言曌
- * @date 2017/12/9 下午4:10
- */
- public interface ArticleService {
- //獲得文章列表
- Page<ArticleVO> findAll(Pageable pageable);
- }
2、ArticleServiceImpl.java
- package com.liuyanzhao.blog.service.Impl;
- import com.liuyanzhao.blog.dao.ArticleDao;
- import com.liuyanzhao.blog.service.ArticleService;
- import com.liuyanzhao.blog.vo.ArticleVO;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.data.domain.Page;
- import org.springframework.data.domain.Pageable;
- import org.springframework.stereotype.Service;
- import javax.transaction.Transactional;
- /**
- * @author 言曌
- * @date 2017/12/9 下午4:10
- */
- @Service("articleService")
- @Transactional
- public class ArticleServiceImpl implements ArticleService {
- @Autowired
- private ArticleDao articleDao;
- @Override
- public Page<ArticleVO> findAll(Pageable pageable) {
- Page<ArticleVO> articleVOPage = articleDao.findAllByOrderByStatusDescIdDesc(pageable);
- return articleVOPage;
- }
- }
Controller 層
ArticleController.java
- package com.liuyanzhao.blog.controller;
- import com.liuyanzhao.blog.service.ArticleService;
- import com.liuyanzhao.blog.vo.ArticleVO;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.data.domain.Page;
- import org.springframework.data.domain.PageRequest;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.*;
- import org.springframework.web.servlet.ModelAndView;
- /**
- * @author 言曌
- * @date 2017/11/28 下午3:33
- */
- @Controller
- public class ArticleController {
- @Autowired
- private ArticleService articleService;
- @RequestMapping(value = "/admin/article")
- public ModelAndView listUser(@RequestParam(value = "page",defaultValue = "1") Integer page,
- @RequestParam(value = "size",defaultValue = "10") Integer size) {
- ModelAndView modelAndView = new ModelAndView();
- PageRequest request = new PageRequest(page-1,size);
- Page<ArticleVO> articleVOPage = articleService.findAll(request);
- modelAndView.addObject("articleVOPage",articleVOPage);
- modelAndView.setViewName("/admin/article/list");
- return modelAndView;
- }
- }
檢視層
檢視層主要看錶格的列印吧,分頁部分和其他內容就不貼出來了
- <table class="table table-bordered">
- <tr>
- <th><input type="checkbox" id="allSelect" onclick="DoCheck()"></th>
- <th>ID</th>
- <th>作者</th>
- <th>標題</th>
- <th>分類</th>
- <th>更新時間</th>
- <th>操作</th>
- </tr>
- <c:forEach var="article" items="${articleVOPage.content}">
- <tr>
- <td><input type="checkbox" name="ids" value="${article.id}"></td>
- <td>${article.id}</td>
- <td>${article.userId}</td>
- <td><a href="">${article.title}</a></td>
- <td>
- <c:forEach var="c" items="${article.articleCategoryList}">
- <a href="">${c.category.name}</a>
- </c:forEach>
- </td>
- <td>${article.updateTime}</td>
- <td>
- <a href="${pageContext.request.contextPath}/admin/user/profile/${article.id}">
- <button type="button" class="btn btn-success btn-xs">檢視</button>
- </a>
- <button type="button" class="btn btn-danger btn-xs"
- onclick="deleteUser(${article.id})">刪除
- </button>
- <a href="${pageContext.request.contextPath}/admin/user/edit/${article.id}">
- <button type="button" class="btn btn-primary btn-xs">編輯</button>
- </a>
- </td>
- </tr>
- </c:forEach>
- </table>
最終效果圖就是上面的
相關文章
- JPA多表關聯查詢
- Spring Data JPA 實現聯表查詢Spring
- Spring Data Jpa 複雜查詢總結 (多表關聯 以及 自定義分頁 )Spring
- JPA 之 多表聯合查詢
- Spring data jpa 多表查詢(三:多對多關係動態條件查詢)Spring
- spring data jpa查詢Spring
- jpa動態查詢與多表聯合查詢
- spring data jpa 多對一聯表查詢Spring
- Spring-Data-JPA criteria 查詢Spring
- MySQL多表關聯查詢MySql
- Spring Data Jpa 的簡單查詢多表查詢HQL,SQL ,動態查詢, QueryDsl ,自定義查詢筆記SpringSQL筆記
- Spring Data JPA + QueryDSL實現CRUD和複雜查詢案例Spring
- Spring JPA 聯表查詢Spring
- spring data jpa關聯查詢(一對一、一對多、多對多)Spring
- JPA的多表複雜查詢
- DataSet多表關聯實現本地資料複雜的查詢
- 實現多表關聯來方便你的SELECT查詢功能
- 如何做多表關聯查詢
- mysql中的多表關聯查詢MySql
- thinkphp中的多表關聯查詢PHP
- MyBatisPlus怎麼多表關聯查詢?MyBatis
- SpringMVC+Spring Data JPA +Bootstrap 分頁實現和模糊查詢分頁SpringMVCboot
- Spring Boot入門系列(十七)整合Mybatis,建立自定義mapper 實現多表關聯查詢!Spring BootMyBatisAPP
- SpringBoot JPA 表關聯查詢Spring Boot
- spring data JPA 模糊查詢 --- 使用 LIKE --- 的寫法Spring
- mysql多表查詢如何實現MySql
- onethinkphp 如何做多表關聯查詢PHP
- thinkPHP多表聯合查詢PHP
- SpringMVC+Spring Data JPA實現增刪改查操作SpringMVC
- Mybatis 多表關聯查詢(1) one-to-one關係MyBatis
- SQL優化之多表關聯查詢-案例一SQL優化
- Spring JPA聯表情況下的複雜查詢Spring
- 使用mybatis example 和 java 8的特性來實現多表關聯且帶有查詢條件的查詢MyBatisJava
- 多表關聯查詢中,關聯欄位都應該建立索引嗎?索引
- Mybatis【15】-- Mybatis一對一多表關聯查詢MyBatis
- mybatis學習 - 多表查詢的實現MyBatis
- Spring Data JpaSpring
- Spring Data JPA之Spring Data JPA快速入門(三)Spring