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