Vue结合spring-data-jap + swagger 的分页查询和CRUD
程序员文章站
2022-07-14 08:48:51
...
Vue结合spring-data-jap + swagger 的分页查询和CRUD
1、基本配置
1.1、配置pom.xml
org.springframework.boot spring-boot-starter-data-jpa org.springframework.boot spring-boot-starter-web<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- swagger的依赖 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
1.2、 配置yml文件
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8
password: root
username: root
jpa:
database: mysql
hibernate:
ddl-auto: update
naming:
implicit-strategy: org.hibernate.boot.model.naming.ImplicitNamingStrategyComponentPathImpl
physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
show-sql: true
1.3、 创建实体类
@Data
@Entity
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
private String sex;
private Integer gradeId;
}
1.4、 配置DAO层
public interface StudentDao extends JpaRepository<Student,Integer>, JpaSpecificationExecutor<Student> {
@Query(value = "select * from Student where name like concat('%',?,'%') ",nativeQuery = true)
Page<Student> getAllByPage(String name, PageRequest pageRequest);
}
1.5、 实现类
@Service
@Transactional
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentDao studentDao;
// 新增的方法
@Override
public Student save(@RequestBody Student student) {
return this.studentDao.save(student);
}
// 分页查询的方法
@Override
public Page<Student> getAllByPage(Integer page,String name) {
Integer size = 2;
if(page == null){
page = 1;
}
PageRequest of = PageRequest.of(page - 1,size);
Page<Student> pages;
if(name == null){
pages =this.studentDao.findAll(of);
}else{
pages = this.studentDao.getAllByPage(name,of);
}
return pages;
}
// 修改的方法
@Override
public Student update(Student student) {
return this.studentDao.save(student);
}
// 删除的方法
@Override
public void delete(Integer id) {
this.studentDao.deleteById(id);
}
public List<Student> getAll() {
return this.studentDao.findAll();
}
}
1.6、controller
@RestController
@RequestMapping("/student")
@Api("swagger ui 注释 api 级别")
public class StudentController {
@Autowired
private StudentServiceImpl studentService;
// 分页查询
@GetMapping("/getAllByPage")
@ApiOperation(value = "分页查询所有学生",notes = "分页查询所有学生")
public Page<Student> getAllByPage(Integer page,String name){
return this.studentService.getAllByPage(page,name);
}
// 新增信息
@PostMapping("/save")
@ApiOperation(value = "新增学生信息",notes = "新增学生信息")
public Student save(@RequestBody Student student){
return this.studentService.save(student);
}
// 删除信息
@DeleteMapping("delete")
@ApiOperation(value = "删除学生信息",notes = "删除学生信息")
public int delete(Integer id){
try {
this.studentService.delete(id);
return 1;
}catch (Exception e){
e.printStackTrace();
return 0;
}
}
// 修改信息
@PutMapping("/update")
@ApiOperation(value = "修改学生信息",notes = "修改学生信息")
public Student update(Student student){
return this.studentService.update(student);
}
}
1.7、 swagger的基本配置
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.chenghu.springdata_vue.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Spring Boot中使用Swagger2实现前后端分离开发")
.description("此项目只是练习如何实现前后端分离开发的小Demo")
.termsOfServiceUrl("https://blog.csdn.net/ca1993422")
.contact("作者")
.version("1.0")
.build();
}
}
1.8、 跨域配置
@Configuration
public class WebConfig implements WebMvcConfigurer {
//跨域配置
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
//重写父类提供的跨域请求处理的接口
public void addCorsMappings(CorsRegistry registry) {
//添加映射路径
registry.addMapping("/**")
//放行哪些原始域
.allowedOrigins("*")
//是否发送Cookie信息
.allowCredentials(true)
//放行哪些原始域(请求方式)
.allowedMethods("GET", "POST", "PUT", "DELETE")
//放行哪些原始域(头部信息)
.allowedHeaders("*")
//暴露哪些头部信息(因为跨域访问默认不能获取全部头部信息)
.exposedHeaders("Header1", "Header2");
}
};
}
}
2、页面接受数据和调用方法
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<!-- 通过CDN引入Vue.js -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<!-- 通过CDN引入axios -->
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<div id="app">
<template>
<input type="text" placeholder="学生姓名" v-model="name">
<button type="button" @click="cx">查询</button>
</template>
<table border="1" cellspacing="0" cellpadding="20">
<tr>
<th>编号</th>
<th>姓名</th>
<th>性别</th>
<th>年级</th>
<th>操作</th>
</tr>
<template v-for="student in students.content">
<tr>
<td>{{student.id}}</td>
<td>{{student.name}}</td>
<td>{{student.sex}}</td>
<td>{{student.gradeId}}</td>
<td>
<a href="#" @click="Delete(student.id)">删除</a>
<a href="#" @click="Edit(student.id)">编辑</a>
</td>
</tr>
</template>
<template>
<td><input type="text" placeholder="学生学号" readonly="readonly" v-model="student.id"/></td>
<td><input type="text" placeholder="学生姓名" v-model="student.name"></td>
<td><input type="text" placeholder="学生性别" v-model="student.sex"></td>
<td><input type="text" placeholder="学生年级" v-model="student.gradeId"></td>
<td>
<button type="button" @click="Save">保存</button>
</td>
</template>
</table>
<template>
<a href="javascript:void(0);" @click="pgUd(0)" style="margin-right: 20px;">首页</a>
<a href="javascript:void(0);" @click="pgUd(students.number)" style="margin-right: 20px;">上一页</a>
<a href="javascript:void(0);" @click="pgUd(students.number+2)" style="margin-right: 20px;">下一页</a>
<a href="javascript:void(0);" @click="pgUd(students.totalPages+1)" style="margin-right: 20px;">尾页</a>
<span>当前页:{{students.number+1}}</span>
</template>
</div>
<script type="text/javascript">
var app = new Vue({
el: '#app',
data: {
student: {
id: '',
name: '',
sex: '',
gradeId: ''
},
students: [],
name: ''
},
methods: {
findAll: function(page,name) {
var _this = this;
axios.get('http://localhost:8080/student/getAllByPage',{
params: {
page: page,
name: _this.name
}
})
.then(function(response) {
_this.students = response.data;
})
.catch(function(error) {
console.log(error);
});
},
Save: function() {
var _this = this;
var student = JSON.stringify(_this.student)
if (student.id != null && student.id != '') { //修改
axios.put('http://localhost:8080/student/update', student, {
headers: {
"Content-Type": "application/json;charset=utf-8" //头部信息
}
})
.then(function(response) {
//保存完之后查询所有的信息
_this.student.name = null;
_this.student.sex = null;
_this.student.gradeId = null;
_this.findAll();
})
.catch(function(error) {
console.log(error);
});
} else { //新增
axios.post('http://localhost:8080/student/save', student, {
headers: {
"Content-Type": "application/json;charset=utf-8" //头部信息
}
})
.then(function(response) {
//保存完之后查询所有的信息
if (_this.student.id != null) {
_this.student.id = null;
}
_this.student.name = null;
_this.student.sex = null;
_this.student.gradeId = null;
_this.findAll();
})
.catch(function(error) {
console.log(error);
});
}
},
Delete: function(sid) {
var _this = this;
axios.delete('http://localhost:8080/student/delete', {
params: {
id: sid
}
})
.then(function(response) {
_this.findAll();
})
.catch(function(error) {
console.log(error);
});
},
Edit: function(student) {
this.student = student;
},
pgUd:function(num){
var pages = this.students.totalPages;
if(num>pages){
num = pages;
}
if(num == 0){
num = 1;
}
this.findAll(num);
},
cx: function(){
this.findAll();
}
},
created: function() { //创建vue对象的时候自动调用查询所有的方法
this.findAll();
}
})
</script>
</body>
</html>
总结
1、单表的CRUD用的很舒服很快,复杂一点的就很麻烦
2、全程用的是Json数据,相当于ajax请求
第一次使用,一点点心得,完全的从建包开始
上一篇: Kubernets
下一篇: WPF的MVVM DataGrid用法