springboot结合vue实现增删改查及分页查询
作者:夜色架构师 时间:2023-11-24 15:53:44
1:首先。创建一个springboot项目,这里我使用以及构建好基本框架的脚手架,打开是这个样子:
Result类:已经封装好了三种返回类型的包装类:code,msg,data
2:创建数据库叫mytest(可以自己取名字)
CREATE TABLE `user` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '序号',
`name` varchar(20) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '姓名·',
`age` int(11) DEFAULT NULL COMMENT '年龄',
`sex` varchar(1) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '性别',
`adderss` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '地址',
`phone` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '电话',
`creat_time` varchar(20) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
3:编写实体类:entity->User类
**首先加@Table注解告诉我们要哪个表,然后加@Entity标注这个User是一个entity,@Data生成getset方法
**
package com.example.entity;
import lombok.Data;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
@Table(name="user")
@Entity
@Data
public class User {
private Long id;
private String name;
private Integer age;
private String sex;
private String adderss;
private String phone;
@Column(name = "creat_time")
private String creatTime;
}
这里可以自己添加get和set方法,我这里是直接在pom里面添加了lombok注解
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
这里user报错不要怕 在下面加上
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY) //表示ID是主见并且自动递增
4:编写UserDao层:写数据库接口
package com.example.dao;
import com.example.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserDao extends JpaRepository<User,Long> {
}
5:编写service层,编写增删改查方法(使用了springdataJPA)
package com.example.service;
import com.example.dao.UserDao;
import com.example.entity.User;
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.stereotype.Service;
import javax.annotation.Resource;
import java.util.Optional;
@Service
public class UserService {
//1:导入数据库接口 (JPA帮助我们编写了大量的接口,我们只需要调用就好)
@Resource
private UserDao userDao;
// 这两个方法合并成了一个,因为都是调用的save,区别就是新增的时候不会传ID进来,更新的时候会,框架会帮我们区分
// // 增加
// public void add(User user){
// userDao.save(user);
// }
//
// //修改
// public void updata(User user){
// userDao.save(user);
//
//新增+修改
public void save(User user){
userDao.save(user);
}
//删除
public void del(Long id){
userDao.deleteById(id);
}
//查找
public User findById(Long id){
return userDao.findById(id).orElse(null); //没有数据则返回null
}
//分页查询
public Page<User> findPage(Integer pageNum, Integer pageSize,String name){
Sort sort = Sort.by(Sort.Direction.DESC,"creat_time");
Pageable request = PageRequest.of(pageNum-1,pageSize,sort);
return userDao.findNameLike(name,request);
}
}
中途需要在UserDao层编写分页查询语句
package com.example.dao;
import com.example.entity.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
@Repository
public interface UserDao extends JpaRepository<User,Long> {
@Query(value = "select * from user where name like %?1%",nativeQuery = true)
Page<User> findNameLike(String name, Pageable pageRequest);
}
6:编写UserController作为接口访问层
package com.example.controller;
import com.example.common.Result;
import com.example.entity.User;
import com.example.service.UserService;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
/**
* @author ${范涛之}
* @Description
* @create 2021-09-20 12:19
*/
@RestController //表明所有方法都是返回json数据
@RequestMapping("/user")
public class UserController {
@Resource
private UserService userService;
// 新增
@PostMapping
public Result add(@RequestBody User user){
userService.save(user);
return Result.success();
}
//更新
@PutMapping
public Result update(@RequestBody User user){
userService.save(user);
return Result.success();
}
//删除用户 : /user/1
@DeleteMapping("/{id}")
public Result delete(@PathVariable Long id){
userService.del(id);
return Result.success();
}
//根据id查询用户
@GetMapping("/{id}")
public Result<User> findById(@PathVariable Long id){
return Result.success( userService.findById(id));
}
//分页查询
@GetMapping
public Result<Page<User>> findById(@RequestParam(required = false,value ="1" )Integer pageNum,
@RequestParam(required = false,value ="10" )Integer PageSize,
@PathVariable(required = false) String name){
return Result.success( userService.findPage(pageNum,PageSize,name));
}
}
7:编写前端界面,在static里面写index.html,测试运行
8:通过使用elementui引入样式
9:编写index.html文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用户信息</title>
<!-- 引入样式 -->
<link rel="stylesheet" href="element.css">
</head>
<body>
<div id="app" style="width: 80%; margin: 0 auto">
<h2>用户信息表</h2>
<el-row>
<el-col :span="6" style="margin-bottom: 10px">
<el-button type="primary" @click="add">新增</el-button>
<el-input v-model="name" style="width: 70%" @keyup.enter.native="loadTable(1)"></el-input>
</el-col>
</el-row>
<el-table
:data="page.content"
stripe
border
style="width: 100%">
<el-table-column
prop="name"
label="用户名"
>
</el-table-column>
<el-table-column
prop="age"
label="年龄"
width="180">
</el-table-column>
<el-table-column
prop="sex"
label="性别">
</el-table-column>
<el-table-column
prop="address"
label="地址">
</el-table-column>
<el-table-column
prop="phone"
label="电话">
</el-table-column>
<el-table-column
fixed="right"
label="操作"
width="100">
<template slot-scope="scope">
<el-button type="primary" icon="el-icon-edit" size="small" circle @click="edit(scope.row)"></el-button>
<el-button type="danger" icon="el-icon-delete" size="small" circle @click="del(scope.row.id)"></el-button>
</template>
</el-table-column>
</el-table>
<el-row type="flex" justify="center" style="margin-top: 10px">
<el-pagination
layout="prev, pager, next"
:page-size="pageSize"
:current-page="pageNum"
@prev-click="loadTable"
@current-change="loadTable"
@next-click="loadTable"
:total="page.totalElements">
</el-pagination>
</el-row>
<el-dialog
title="用户信息"
:visible.sync="dialogVisible"
width="30%">
<el-form ref="form" :model="form" label-width="80px">
<el-form-item label="用户名">
<el-input v-model="form.name"></el-input>
</el-form-item>
<el-form-item label="年龄">
<el-input v-model="form.age"></el-input>
</el-form-item>
<el-form-item label="性别">
<el-radio v-model="form.sex" label="男">男</el-radio>
<el-radio v-model="form.sex" label="女">女</el-radio>
</el-form-item>
<el-form-item label="地址">
<el-input v-model="form.address"></el-input>
</el-form-item>
<el-form-item label="电话">
<el-input v-model="form.phone"></el-input>
</el-form-item>
</el-form>
<span slot="footer" class="dialog-footer">
<el-button @click="dialogVisible = false">取 消</el-button>
<el-button type="primary" @click="save">确 定</el-button>
</span>
</el-dialog>
</div>
<script src="jquery.min.js"></script>
<script src="vue.js"></script>
<!-- 引入组件库 -->
<script src="element.js"></script>
<script>
new Vue({
el: '#app',
data: {
page: {},
name: '',
pageNum: 1,
pageSize: 8,
dialogVisible: false,
form: {}
},
created() {
this.loadTable(this.pageNum);
},
methods: {
loadTable(num) {
this.pageNum = num;
$.get("/user/page?pageNum=" + this.pageNum + "&pageSize=" + this.pageSize + "&name=" + this.name).then(res => {
this.page = res.data;
});
},
add() {
this.dialogVisible = true;
this.form = {};
},
edit(row) {
this.form = row;
this.dialogVisible = true;
},
save() {
let data = JSON.stringify(this.form);
if (this.form.id) {
// 编辑
$.ajax({
url: '/user',
type: 'put',
contentType: 'application/json',
data: data
}).then(res => {
this.dialogVisible = false;
this.loadTable(1);
})
} else {
// 新增
$.ajax({
url: '/user',
type: 'post',
contentType: 'application/json',
data: data
}).then(res => {
this.dialogVisible = false;
this.loadTable(1);
})
}
},
del(id) {
$.ajax({
url: '/user/' + id,
type: 'delete',
contentType: 'application/json'
}).then(res => {
this.loadTable(1);
})
}
}
})
</script>
</body>
</html>
完结撒花:
来源:https://blog.csdn.net/justleavel/article/details/120389400
标签:springboot,vue,增删改查,分页查询
0
投稿
猜你喜欢
Java使用Math.random()结合蒙特卡洛方法计算pi值示例
2023-05-10 10:43:13
Java Web实现简易图书管理系统
2023-12-17 21:48:34
Python实现JavaBeans流程详解
2021-05-29 05:37:39
Android选项菜单用法实例分析
2022-11-02 07:42:44
JAVA并发中VOLATILE关键字的神奇之处详解
2021-08-15 01:51:38
MyBatis配置的应用与对比jdbc的优势
2023-08-27 07:03:47
详解Spring Security认证流程
2022-04-16 15:48:46
详解Java使用Pipeline对Redis批量读写(hmset&hgetall)
2023-11-17 15:17:24
vue+springboot前后端分离工程跨域问题解决方案解析
2023-08-06 06:51:10
Java 深入探究讲解简单工厂模式
2022-12-25 12:02:06
RestTemplate使用不当引发的问题及解决
2023-01-21 11:27:19
java实现简单验证码生成
2022-06-02 10:05:09
详解androidstudio项目上传到github方法以及步骤
2023-07-15 02:55:42
Java 回调函数深入理解
2023-11-01 17:32:04
java泛型中占位符T和?有什么区别
2022-07-05 02:53:56
sms4j 2.0 全新来袭功能的调整及maven变化详解
2023-11-05 00:31:51
Java 中Comparable和Comparator区别比较
2023-10-28 23:16:34
详解Java字节码编程之非常好用的javassist
2021-08-27 04:54:30
java组件commons-fileupload实现文件上传、下载、在线打开
2022-02-24 22:16:59
Spring Boot 启动加载数据 CommandLineRunner的使用
2021-06-17 12:52:21