最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

JPA實(shí)現(xiàn)多表連接查詢過程

 更新時(shí)間:2026年06月02日 10:46:54   作者:Cccccccccc22  
這篇文章主要介紹了JPA實(shí)現(xiàn)多表連接查詢過程,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

一、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

JPA 官方參考文檔

二、任務(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)文章

最新評論

县级市| 化州市| 霍邱县| 兴化市| 汽车| 延吉市| 连云港市| 修武县| 进贤县| 安龙县| 乌拉特后旗| 泸水县| 沅陵县| 江北区| 宜都市| 福建省| 九台市| 常宁市| 苏尼特左旗| 循化| 台安县| 新郑市| 蓬安县| 汉中市| 宜丰县| 南京市| 文昌市| 商都县| 栾城县| 勐海县| 双江| 双柏县| 翁牛特旗| 洛浦县| 天镇县| 峨边| 福海县| 睢宁县| 宁晋县| 新龙县| 长子县|