JPA實(shí)現(xiàn)多表連接查詢過程
一、JPA
JPA 定義
Java 持久化 API
Java 官方定義的 ORM 規(guī)范,只是一套規(guī)范,并沒有提供底層的實(shí)現(xiàn)(基于抽象工廠設(shè)計(jì)模式,將定義與實(shí)現(xiàn)解耦),Hibernate 、TopLink 都是 JPA 的提供商,它們實(shí)現(xiàn)了 JPA 規(guī)范
JPA 基于注解的方式實(shí)現(xiàn)了 實(shí)體類 到 關(guān)系表 之間的映射
- @Entity
- @Table
- @Id
- @Column
- @OneToOne
- @OneToMany
- @ManyToOne
二、任務(wù)
使用 MySQL 提供的實(shí)例數(shù)據(jù)庫 world,基于 JPA 設(shè)計(jì)兩個(gè)實(shí)體 City 和 Country 映射數(shù)據(jù)庫中已存在的表,實(shí)現(xiàn)多表連接查詢,在 UI 界面分頁顯示每個(gè)城市的信息:
- 編號
- 城市名稱
- 城市人口
- 所在國家
- 所屬洲
要點(diǎn):根據(jù) city 表中的 countrycode 字段 與 country 表中的 code 字段進(jìn)行匹配,實(shí)現(xiàn)多表查詢

實(shí)戰(zhàn)
1.項(xiàng)目結(jié)構(gòu)

2.項(xiàng)目配置信息

3.實(shí)體
- City
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
import javax.persistence.Table;
@Entity
@Table(name = "city")
public class City {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;
String name;
Long population;
@ManyToOne//(targetEntity = Country.class)
@JoinColumn(name="countrycode",referencedColumnName = "code")
Country country;
public City() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getPopulation() {
return population;
}
public void setPopulation(Long population) {
this.population = population;
}
public Country getCountry() {
return country;
}
public void setCountry(Country country) {
this.country = country;
}
@Override
public String toString() {
return "City [id=" + id + ", name=" + name + ", population=" + population + ", country=" + country + "]";
}
}
- Country
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "country")
public class Country {
@Id
String code;
String name;
String continent;
public Country() {
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getContinent() {
return continent;
}
public void setContinent(String continent) {
this.continent = continent;
}
@Override
public String toString() {
return "Country [code=" + code + ", name=" + name + ", continent=" + continent + "]";
}
}
4.映射
- CityRepository
無需自定義業(yè)務(wù)邏輯,直接繼承接口即可,該接口支持分頁和排序
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface CityRepository extends PagingAndSortingRepository<City, Long>{
}
- CountryRepository
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface CountryRepository extends PagingAndSortingRepository<Country, String>{
}
5.控制器
- HomeController
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HomeController {
// 返回視圖
@GetMapping("/")
public String home() {
return "index.html";
}
}
- CityController
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/city")
public class CityController {
@Autowired
CityRepository cityRepository;
/**
* GET '/api/city'
*
* @param page 當(dāng)前頁碼
* @param size 每頁的記錄數(shù)默認(rèn)設(shè)定為10,一頁加載10條
* @return
*/
@GetMapping
public Page<City> findCity(
@RequestParam(name = "p",defaultValue = "0") int page,
@RequestParam(name = "n",defaultValue = "10") int size){
// 分頁規(guī)則
Pageable pageable = PageRequest.of(page, size);
// 可按城市人口數(shù)量進(jìn)行降序排序
pageable = PageRequest.of(page, size,Sort.by("population").descending());
return cityRepository.findAll(pageable);
}
}
6.UI
基于 Vue、AJAX、Bootstrap
<!doctype html>
<html lang="en">
<head>
<title>City</title>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" rel="external nofollow" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<!-- Vue js-->
<script src="js/vue.js"></script>
<!-- AJAX js-->
<script src="js/axios.min.js"></script>
</head>
<body>
<!-- View UI-->
<div id="app">
<!-- 展板 -->
<div class="jumbotron jumbotron-fluid py-1 pl-5 mb-0">
<div class="container">
<h1 class="display-3">Cities Of The World</h1>
<p class="lead">基于 <span class="badge badge-pill badge-danger">JPA</span> 分頁顯示</p>
<p class="lead">作者:某某某</p>
</div>
</div>
<!-- 容器 -->
<div class="container-fluid">
<!-- 表格 -->
<table class="table table-striped table-bordered mt-2">
<!-- 表頭 -->
<thead class="table-dark">
<tr class="text-center">
<th style="width: 3em;">
<input type="checkbox">
</th>
<th style="width: 8em;">編號</th>
<th style="width: 20em;">城市名稱</th>
<th style="width: 10em;">城市人口 [↓]</th>
<th>所在國家</th>
<th style="width: 18em;">所屬洲</th>
</tr>
</thead>
<!-- 表體 -->
<tbody>
<!-- v-for 聲明式渲染 城市數(shù)據(jù) -->
<tr v-for="(city, index) in cityList" :key="index">
<td class="text-center">
<input type="checkbox">
</td>
<td class="text-center">{{city.id}}</td>
<td>{{city.name}}</td>
<td>{{city.population}}</td>
<td>{{city.country.name}}</td>
<td>{{city.country.continent}}</td>
</tr>
</tbody>
</table>
</div>
<!-- 分頁導(dǎo)航 -->
<nav aria-label="Page navigation">
<ul class="pagination justify-content-center">
<!-- 上一頁 -->
<li class="page-item" @click="prevPage()" :class="{'disabled':isFirst}">
<a class="page-link" href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" aria-label="Previous">
<span aria-hidden="true">上一頁</span>
<span class="sr-only">Previous</span>
</a>
</li>
<!-- v-for 聲明式渲染 頁碼 -->
<li class="page-item" :class="{active : (n-1)===currentPage}" @click="page(n-1)" v-for="n in totalPages" v-if="showPage(n)" :key="n">
<a class="page-link" href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" >{{showPage(n)}}</a>
</li>
<!-- 下一頁 -->
<li class="page-item" @click="nextPage()" :class="{'disabled':isLast}">
<a class="page-link" href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" aria-label="Next">
<span aria-hidden="true">下一頁</span>
<span class="sr-only">Next</span>
</a>
</li>
<!-- 頁碼快速定位 -->
<li>
<!-- 輸入頁碼按回車鍵即可跳轉(zhuǎn) 或者 點(diǎn)擊跳轉(zhuǎn)按鈕-->
轉(zhuǎn)到 <input @keyup.enter="goPage()" style="width: 3em;" type="text" v-model="goPageIndex"> 頁
<button class="btn btn-outline-warning " @click="goPage()">跳轉(zhuǎn)</button>
</li>
</ul>
</nav>
</div>
<!-- JS -->
<Script>
// 創(chuàng)建一個(gè) Vue 實(shí)例
let v = new Vue({
// 綁定
el: '#app',
// 數(shù)據(jù)
data: {
// 城市列表
cityList: [],
// 總頁碼
totalPages: 0,
// 當(dāng)前頁碼
currentPage: 0,
// 是否第一頁
isFirst: '',
// 是否最后一頁
isLast: '',
// 輸入的頁碼
goPageIndex: ''
},
// 方法
methods: {
// 加載數(shù)據(jù)
loadCityList: function() {
// GET '/api/city'
const url = '/api/city';
axios.get(url)
.then(res => {
console.log('加載城市列表數(shù)據(jù)', res.data);
// 城市列表
this.cityList = res.data.content;
// 當(dāng)前頁
this.currentPage = res.data.number;
// 總頁數(shù)
this.totalPages = res.data.totalPages;
// 狀態(tài)
this.isFirst = res.data.first;
this.isLast = res.data.last;
})
.catch(err => {
console.error(err);
})
},
// 點(diǎn)擊頁碼進(jìn)行跳轉(zhuǎn)
page: function(n) {
// GET '/api/city?p=123'
const url = `/api/city?p=${n}`;
axios.get(url)
.then(res => {
console.log('換頁', n + 1);
this.cityList = res.data.content;
this.totalPages = res.data.totalPages;
this.currentPage = res.data.number;
})
.catch(err => {
console.error(err);
})
},
// 上一頁
prevPage: function() {
if (this.currentPage > 0) {
this.currentPage -= 1;
this.page(this.currentPage);
} else {
return;
}
},
// 下一頁
nextPage: function() {
if (this.currentPage < this.totalPages - 1) {
this.currentPage += 1;
this.page(this.currentPage);
} else {
return;
}
},
// 輸入頁碼快速定位
goPage: function() {
let goPageIndex = parseInt(this.goPageIndex);
if (goPageIndex > 0 && goPageIndex <= this.totalPages) {
this.page(this.goPageIndex - 1);
this.goPageIndex = '';
}
},
// 頁碼過多時(shí)顯示省略號
showPage(n) {
// 前兩個(gè)和最后兩個(gè)始終顯示
if (n < 3 || (n > this.totalPages - 2)) {
return n;
}
// 當(dāng)前頁的前一頁和后一頁始終顯示
else if (n <= this.currentPage + 2 && n >= this.currentPage) {
return n;
}
// 當(dāng)前頁的前前頁和后后頁顯示 ...
else if (n === this.currentPage + 3 || n === this.currentPage - 1) {
return '...';
}
// 其余的不顯示
else {
return false;
}
}
},
// 回調(diào)函數(shù)
// 創(chuàng)建頁面時(shí)自動調(diào)用 加載數(shù)據(jù)
created() {
this.loadCityList();
},
})
</Script>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>三、效果圖
每頁10條記錄,切分成408頁,按照城市人口進(jìn)行降序排序

總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
idea運(yùn)行java項(xiàng)目main方法報(bào)build failure錯(cuò)誤的解決方法
當(dāng)在使用 IntelliJ IDEA 運(yùn)行 Java 項(xiàng)目的 main 方法時(shí)遇到 "Build Failure" 錯(cuò)誤,這通常意味著在項(xiàng)目的構(gòu)建過程中遇到了問題,以下是一些詳細(xì)的解決步驟,以及一個(gè)簡單的代碼示例,用于展示如何確保 Java 程序可以成功構(gòu)建和運(yùn)行,需要的朋友可以參考下2024-09-09
SpringBoot集成mqtt的多模塊項(xiàng)目配置詳解
這篇文章主要介紹了SpringBoot集成mqtt的多模塊項(xiàng)目配置詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04
java使用WatchService監(jiān)控文件夾示例
本篇文章主要介紹了java使用WatchService監(jiān)控文件夾示例的資料,這里整理了詳細(xì)的代碼,有需要的小伙伴可以參考下。2017-02-02
SpringMVC HttpMessageConverter報(bào)文信息轉(zhuǎn)換器
??HttpMessageConverter???,報(bào)文信息轉(zhuǎn)換器,將請求報(bào)文轉(zhuǎn)換為Java對象,或?qū)ava對象轉(zhuǎn)換為響應(yīng)報(bào)文。???HttpMessageConverter???提供了兩個(gè)注解和兩個(gè)類型:??@RequestBody,@ResponseBody???,??RequestEntity,ResponseEntity??2023-01-01
解決Maven項(xiàng)目本地公共common包緩存問題
這篇文章主要介紹了解決Maven項(xiàng)目本地公共common包緩存問題,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-09-09
Java實(shí)現(xiàn)的獲取和判斷文件頭信息工具類用法示例
這篇文章主要介紹了Java實(shí)現(xiàn)的獲取和判斷文件頭信息工具類,結(jié)合實(shí)例形式分析了Java針對文件讀取及頭信息判斷相關(guān)操作技巧,需要的朋友可以參考下2017-11-11
java實(shí)現(xiàn)圖片轉(zhuǎn)base64字符串 java實(shí)現(xiàn)base64字符串轉(zhuǎn)圖片
這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)圖片轉(zhuǎn)base64字符串,java實(shí)現(xiàn)base64字符串轉(zhuǎn)圖片,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-02-02
Maven配置文件修改及導(dǎo)入第三方j(luò)ar包的實(shí)現(xiàn)
本文主要介紹了Maven配置文件修改及導(dǎo)入第三方j(luò)ar包的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-08-08
Java高效實(shí)現(xiàn)合并多個(gè)Word文檔的實(shí)戰(zhàn)指南
在企業(yè)開發(fā)和日常辦公自動化中,我們經(jīng)常需要處理 Word 文檔,本文將系統(tǒng)講解在 Java 中合并 Word 文檔的常用方法,提供完整示例,幫助你快速掌握文檔合并技巧2026-01-01

