SpringDataJPA+vue前後端分離實現三級聯動

SpringDataJPA+vue前後端分離實現三級聯動

一、編寫後端代碼

1、創建springdatajpa項目,添加jdbc、jpa、web、mysql依賴,並創建對應的層
2、創建對應數據庫,編寫省、市、區的實體類(idea需要使用lombok插件)

城市實體類(toString()方法可寫可不寫,只是方便從控制檯輸出的數據)
/**
 * 城市實體類
 */
@Data
@Entity
@Table(name = "t_address_city")
public class City implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id",insertable = false,updatable = false)
    private int id;

    @Column(name = "code")
    private String code;

    @Column(name = "name")
    private String name;

    @Column(name = "province_code")
    private String provinceCode;
    /**
     * 一個城市對應多個城區
     */
    @OneToMany(targetEntity = Town.class,fetch = FetchType.LAZY)
    @JoinColumn(name = "city_code",referencedColumnName = "code")
    private Set<Town> areaList = new HashSet<>();
}
省份實體類
/**
 * 省份實體類
 */
@Data
@Entity
@Table(name = "t_address_province")
public class Province implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id",updatable = false,insertable = false)
    private int id;

    @Column(name = "code")
    private String code;//省份編碼

    @Column(name = "name")
    private String name;    //省份名稱

    //一個省份對應多個城市
    @OneToMany(targetEntity = City.class,fetch =FetchType.EAGER)
    @JoinColumn(name = "province_code",referencedColumnName = "code")
    private Set<City> cityList = new HashSet<>();

    @Override
    public String toString() {
        return "Province{" +
                "id=" + id +
                ", code='" + code + '\'' +
                ", name='" + name + '\'' +
                ", cityList=" +
                '}';
        //cityList +
    }
}
縣區實體類
**
 *  縣區實體類
 */
@Data
@Entity
@Table(name = "t_address_town")
public class Town {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id",insertable = false,updatable = false)
    private int id;

    @Column(name = "code")
    private String code;

    @Column(name = "name")
    private String name;

    @Column(name = "city_code")
    private String cityCode;

    @Override
    public String toString() {
        return "Town{" +
                "id=" + id +
                ", code='" + code + '\'' +
                ", name='" + name + '\'' +
                ", cityCode='" + cityCode + '\'' +
                '}';
    }
}

3、編寫dao層
省份數據訪問層

/**
 * 省份數據訪問層
 */
public interface ProvinceDao extends JpaRepository<Province,Integer> {

}

城市數據訪問層

/**
 * 城市數據訪問層
 */
public interface CityDao extends JpaRepository<City,Integer> {
    /**
     * 根據省份編號查詢城市信息
     * @param provinceCode
     * @return
     */
    List<City> findCitiesByProvinceCode(String provinceCode);
}

縣區數據訪問層

/**
 * 縣區數據訪問層
 */
public interface TownDao extends JpaRepository<Town,Integer> {
    /**
     * 根據城市編號查詢城市信息
     * @param cityCode
     * @return
     */
    List<Town> findTownsByCityCode(String cityCode);
}

4、編寫service層,調用對應的dao接口,返回相應數據類型
省份服務層

@Service
@Transactional
public class ProvinceService {

    @Autowired
    private ProvinceDao provinceDao;
    /**
     * 查詢全部信息
     * @return
     */
    public List<Province> findProvince(){
        return provinceDao.findAll();
    }
}

5、編寫web層,調用service方法

/**
 * 三級聯動Controller
 */
@RestController
public class JlController {
    @Autowired
    private ProvinceService provinceService;
    /**
     * 查詢所有省份信息
     * @return
     */
    @GetMapping("/province")
    public List<Province> findAll(){
        return provinceService.findProvince();
    }
}

6、編寫config層,實現跨域請求

/**
 * 全局跨域配置文件
 */
@Configuration
public class GlobalCorsConfig {
    @Bean
    public CorsFilter corsFilter() {
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        final CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setAllowCredentials(true);
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", corsConfiguration);


        //1.添加CORS配置信息
        final CorsConfiguration config = new CorsConfiguration();
        //1) 允許的域,不要寫*,否則cookie就無法使用了
//        config.addAllowedOrigin("http://www.leyou.com");
//        config.addAllowedOrigin("http://api.leyou.com");
//        config.addAllowedOrigin("http://manage.leyou.com");
        config.addAllowedOrigin("*");
        //2) 是否發送Cookie信息
        config.setAllowCredentials(true);
        //3) 允許的請求方式
        config.addAllowedMethod("OPTIONS");
        config.addAllowedMethod("HEAD");
        config.addAllowedMethod("GET");
        config.addAllowedMethod("PUT");
        config.addAllowedMethod("POST");
        config.addAllowedMethod("DELETE");
        config.addAllowedMethod("PATCH");
        // 4)允許的頭信息
        config.addAllowedHeader("*");
        //5,有效時長
        config.setMaxAge(3600L);

        //2.添加映射路徑,我們攔截一切請求
        final UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
        configSource.registerCorsConfiguration("/**", config);

        //3.返回新的CorsFilter.
        return new CorsFilter(configSource);
    }
}

6、使用工具Postman測試接口,返回json數據格式
在這裏插入圖片描述
總結:後端相對與前端來說比較簡單,但是由於時間關係,業務邏輯沒有很好的整理清楚,這就導致每次訪問數據庫的時候,直接查詢所有信息,導致對數據庫請求壓力過大,響應緩慢。但是能寫出來就不錯了,希望自己能夠好好學習,再接再厲。

二、前端,Vue + Element-Ui

話不多說,直接上代碼(前端代碼可以直接去Element-Ui官網c代碼 滑稽.jpg)
1、創建vue項目 vue init webpack projectName
2、安裝 axios 插件,在當前項目下的終端輸入命令: npm install --save axios vue-axios
安裝 Element 插件,在當前項目下的終端輸入命令:npm i element-ui -S
3、在 src 文件夾下的程序入口 main.js 中導入

import axios from 'axios'
import VueAxios from 'vue-axios'
// element-ui 引入文件
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
//註冊 VueAxios, axios
Vue.use(VueAxios, axios)
Vue.use(ElementUI)

4、創建vue文件,編寫代碼
使用element下拉組件,編寫三級下拉框,具體參數示例可參考Element官網介紹

<template>
  <div class="hello">
  <b-col md="6">
	<label ></label>
	<el-select v-model="provinceValue" placeholder="請選擇省" @change="chooseProvince">
		<el-option	
    		v-for="item in provinceData"
    		:key="item.code"
    		:label="item.name"
    		:value="item.name">
		</el-option>
	</el-select>
</b-col>
<b-col md="6">
	<label ></label>
	<el-select v-model="cityValue" placeholder="請選擇市" @change="chooseCity">
		<el-option	
    		v-for="item in cityData"
    		:key="item.code"
    		:label="item.name"
    		:value="item.name">
		</el-option>
	</el-select>
</b-col>
<b-col md="6">
	<label >區、縣</label>
	<el-select v-model="areaValue" @change="chooseArea" placeholder="請選擇區、縣">
    	<el-option
	        v-for="item in areaData"
	        :key="item.code"
	        :label="item.name"
	        :value="item.name">
	    </el-option>
    </el-select>
</b-col>
  </div>
</template>

5、綁定數據

<script>
const axios = require("axios")
export default {
  name: 'HelloWorld',
  data () {
    return {
        areaData: [],
        provinceValue:'',
				cityValue:'',
				areaValue:'',
				provinceData:[],
				cityData:[],
				areaData:[],
    }
  },
  created(){//加載時間
    axios.get('http://localhost:8888/province').then(res=>{
				this.provinceData = res.data;
			}).catch(e => {
				this.$message.error("網絡連接超時");
		    })
  },
  methods: {
    chooseProvince(value){
		this.cityValue = '';
		this.areaValue = '';
		this.cityData = [];
		this.areaData = [];
        this.provinceData.map(e=>{ //遍歷數據
			if( value == e.name){
				console.log(value)
				this.cityData = e.cityList;
				return;
			}
		})
	},
	chooseCity(value){
		this.areaValue = '';
		this.cityData.map(e=>{//遍歷數據
			if( value == e.name){
				this.areaData = e.areaList;
				return;
			}
		})
	},
	chooseArea(){
	}
  },
}
</script>

6、運行截圖
在這裏插入圖片描述
前端總結:vue項目主要使用element組件,使用axios的ajax發送請求,通過v-for,v-mode綁定數據。
,前端頁面和後端源碼、sql文件自取
https://pan.baidu.com/s/1Dog8esYOQJC6erOx2EFgkg. 提取碼:robp

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章