文章目录
前言
SpringBoot实现增删改查、分页查询、模糊查询。
统一的设置返回类型
统一的返回数据结构可以使代码更加清晰易懂,方便阅读和维护。例如,当所有接口都返回相同格式的 JSON 数据时,开发人员可以轻松地理解和使用返回的数据,而无需猜测不同接口返回的数据格式。
public class Result {
private static final String SUCCESS ="0";
private static final String ERROR ="-1";
private String code;
private String msg;
private Object data;
public static Result success(){
Result result = new Result();
result.setCode(SUCCESS);return result;}
public static Result success(Object data){
Result result = new Result();
result.setCode(SUCCESS);
result.setData(data);return result;}
public static Result error(String msg){
Result result = new Result();
result.setCode(ERROR);
result.setMsg(msg);return result;}}
Vue安装axios,封装request
npm i axios -S
在src目录下,创建一个utils包,用来存放我们自己定义的工具,在utils包里创建一个request.js,来封装request请求
import axios from 'axios'
// 创建一个axios对象出来
const request = axios.create({
baseURL: 'http://localhost:8080',
timeout: 5000})
// request 拦截器
// 可以自请求发送前对请求做一些处理
// 比如统一加token,对请求参数统一加密
request.interceptors.request.use(config =>{
config.headers['Content-Type']='application/json;charset=utf-8';
// config.headers['token']= user.token; // 设置请求头
return config
}, error =>{return Promise.reject(error)});
// response 拦截器
// 可以在接口响应后统一处理结果
request.interceptors.response.use(
response =>{
// response.data即为后端返回的Result
let res = response.data;
// 兼容服务端返回的字符串数据
if(typeof res ==='string'){
res = res ? JSON.parse(res): res
}return res;},
error =>{
console.log('err' + error) // for debug
return Promise.reject(error)})export default request
查询所有的用户
前端页面请求
我们前端规定要发送的请求和数据是什么。
export default {
name: "AdminView",
data(){return{
tableData: []}},
created(){
this.load();},
methods: {load(){
request.get("/admin").then(res =>{if(res.code ==='0'){
this.tableData = res.data;}})},
}}
后端接口编写
controller
Service
Mapper
@CrossOrigin
@RestController
@RequestMapping("/admin")
public class AdminController {
AdminService adminService;
@Autowired
public AdminController(AdminService adminService){this.adminService=adminService;}
@GetMapping
public Result getUser(){
List<User>list=adminService.getUser();return Result.success(list);}}
public interface AdminService {
public List<User> getUser();}<?xml version="1.0"encoding="UTF-8"?><!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.example.mapper.AdminMapper"><!--2. 基于xml的方式--><select id="getUser"resultType="com.example.entity.User">select * from user
</select></mapper>

如果出现了跨域问题
在controller上加个注解:@CrossOrigin
条件查询
我们的条件查询就是根据电话号码和名字进行模糊查询,下面就让我们开始。
前台请求
按钮控件
<el-input v-model="params.name"style="width: 200px"placeholder="请输入姓名"></el-input><el-input v-model="params.phone"style="width: 200px; margin-left: 5px"placeholder="请输入电话"></el-input><el-button type="warning"style="margin-left: 10px" @click="findBySearch()">查询</el-button>
创建数据
// data里定义一个params
params: {
name: '',
phone: ''},
发送请求
// methods里定义一个findBySearch
findBySearch(){
request.get("/admin/search", {
params: this.params
}).then(res =>{if(res.code ==='0'){
this.tableData = res.data;}else{}})},
后台处理请求
定义实体类Parms接受参数
这里是接受 前端发送的请求
publicclassParams{privateString name;privateString phone;}
定义Controller
@GetMapping("/search")
public Result findBySearch(Params params){
List<Admin>list=adminService.finBySearch(params);return Result.success(list);}
Service层
@Override
public List<Admin> finBySearch(Params params){return adminMapper.findBySearch(params);}
Mapper层
List<Admin> findBySearch(@Param("params") Params params);
<select id="findBySearch"resultType="com.example.entity.Admin">select * from admin
<where><if test="params != null and params.name != null and params.name != ''">
and name like concat('%', #{ params.name }, '%')</if><if test="params != null and params.phone != null and params.phone != ''">
and phone like concat('%', #{ params.phone }, '%')</if></where></select>
加一个小功能,清空查询
<el-button type="warning" @click="reset()">清空</el-button>
reset(){this.params={
name:'',
phone:''}
this.findBySearch()}
分页查询
前台发送请求
设置页面
<div style="margin-top: 10px"><el-pagination
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
:current-page="params.pageNum"
:page-sizes="[5, 10, 15, 20]"
:page-size="params.pageSize"layout="total, sizes, prev, pager, next"
:total="total"></el-pagination></div>
1. @size-change="handleSizeChange"
这也是一个事件绑定,表示当用户改变每页显示的条数 (page-size) 时,会触发 handleSizeChange 方法。
handleSizeChange 方法需要自行定义,负责处理用户改变每页显示条数的逻辑,例如更新 params.pageSize 和重新获取数据。
2. @current-change="handleCurrentChange"
这也是事件绑定。当用户改变当前页 (current-page) 时,会触发 handleCurrentChange 方法。
handleCurrentChange 方法需要自行定义,负责处理用户改变当前页的逻辑,例如更新 params.pageNum 和重新获取数据。
3. :current-page="params.pageNum"
这是绑定,将组件属性 (current-page) 与数据对象 (params) 的属性 (pageNum) 绑定在一起。
在这种情况下,el-pagination 组件的当前页号 (current-page) 将被设置为 params 对象的 pageNum 属性的值。
4. :page-sizes="[5, 10, 15, 20]"
这是使用数组指定 el-pagination 组件中显示的页面大小(每页显示的条目数)的选项。
通过此设置,用户可以选择每页显示 5、10、15 或 20 项。
5. :page-size="params.pageSize"
这也是绑定,将 el-pagination 组件的 page-size 属性与 params 对象的 pageSize 属性绑定在一起。
通过此设置,el-pagination 组件中当前选定的页面大小将被设置为 params 对象的 pageSize 属性的值。
6. layout="total, sizes, prev, pager, next"
这是使用字符串指定 el-pagination 组件的布局。
"total" 显示总条目数。
"sizes" 显示页面大小选项。
"prev" 显示上一页按钮。
"pager" 显示当前页号和总页数。
"next" 显示下一页按钮。
通过此设置,将显示总条目数、页面大小选项、上一页和下一页按钮以及当前页号和总页数。
7. :total="total"
这也是绑定,将 el-pagination 组件的 total 属性与变量 total 绑定在一起。
通过此设置,总条目数将显示在 el-pagination 组件中。
发送请求
params: {
name: '',
phone: '',
pageNum: 1,
pageSize: 5},
total: 0
后台接受请求
- 在pom.xml 加载 分页插件
<dependency><groupId>com.github.pagehelper</groupId><artifactId>pagehelper-spring-boot-starter</artifactId><version>1.2.10</version></dependency>
- 在application.yml拷贝好分页配置
pagehelper:
helper-dialect: mysql
reasonable: true
support-methods-arguments: true
params: count=countSql
PageHelper 配置解释
helper-dialect: 指定数据库方言,这里设置为 mysql,表示使用 MySQL 数据库方言。
reasonable: 开启合理化查询,可以自动优化分页查询语句,提高效率。
support-methods-arguments: 开启对方法参数的支持,可以自动从方法参数中获取分页参数。
params: 配置分页参数,这里配置了 count=countSql,表示使用 countSql 方法计算总记录数。
- 编写Controller接口
@GetMapping("/search")
public Result findBySearch(Params params){
PageInfo<Admin> info = adminService.findBySearch(params);return Result.success(info);}
- Service接口
public PageInfo<Admin> findBySearch(Params params){
// 开启分页查询
PageHelper.startPage(params.getPageNum(), params.getPageSize());
// 接下来的查询会自动按照当前开启的分页设置来查询
List<Admin> list = adminDao.findBySearch(params);return PageInfo.of(list);}
- Mapper层接口
<select id="findBySearch"resultType="com.example.entity.Admin">select * from admin
<where><if test="params != null and params.name != null and params.name != ''">
and name like concat('%', #{ params.name }, '%')</if><if test="params != null and params.phone != null and params.phone != ''">
and phone like concat('%', #{ params.phone }, '%')</if></where></select>
新增、编辑管理员信息
前台
构造页面
<el-button type="warning"style="margin-left: 10px" @click="add()">新增</el-button><el-dialog title="请填写信息" :visible.sync="dialogFormVisible"width="30%"><el-form :model="form"><el-form-item label="姓名" label-width="15%"><el-input v-model="form.name"autocomplete="off"style="width: 90%"></el-input></el-form-item><el-form-item label="性别" label-width="15%"><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="年龄" label-width="15%"><el-input v-model="form.age"autocomplete="off"style="width: 90%"></el-input></el-form-item><el-form-item label="电话" label-width="15%"><el-input v-model="form.phone"autocomplete="off"style="width: 90%"></el-input></el-form-item></el-form><div slot="footer"class="dialog-footer"><el-button @click="dialogFormVisible = false">取 消</el-button><el-button type="primary" @click="submit()">确 定</el-button></div></el-dialog>
构造请求
add(){
this.form ={};
this.dialogFormVisible =true;},
submit(){
request.post("/admin", this.form).then(res =>{if(res.code ==='0'){
this.$message({
message: '操作成功',
type: 'success'});
this.dialogFormVisible =false;
this.findBySearch();}else{
this.$message({
message: res.msg,
type: 'success'});}})}
后台
controller层
@PostMapping()publicResultinsert(@RequestBodyAdmin admin){
adminService.add(admin);returnResult.success();}
Service
publicResultadd(Admin admin){// // 1. 用户名一定要有,否则不让新增(后面需要用户名登录)if(admin.getName()==null||"".equals(admin.getName())){thrownewCustomException("用户名不能为空");}// 2. 进行重复性判断,同一名字的管理员不允许重复新增:只要根据用户名去数据库查询一下就可以了Admin user = adminMapper.findByName(admin.getName());if(user !=null){// 说明已经有了,这里我们就要提示前台不允许新增了thrownewCustomException("该用户名已存在,请更换用户名");}//初始化一个密码if(admin.getPassword()==null){
admin.setPassword("123456");}if(admin.getId()==null){
adminMapper.insert(admin);}else{
adminMapper.updateById(admin);}returnResult.success();}
Mapper
intinsert(Admin admin);
<insert id="insert" parameterType="com.example.entity.Admin" useGeneratedKeys="true">
insert into admin
<trim prefix="(" suffix=")" suffixOverrides=","><if test="id != null">id,</if><if test="username != null">username,</if><if test="password != null">password,</if><if test="name != null">name,</if><if test="phone != null">phone,</if><if test="email != null">email,</if><if test="avatar != null">avatar,</if><if test="role != null">role,</if></trim><trim prefix="values (" suffix=")" suffixOverrides=","><if test="id != null">#{id},</if><if test="username != null">#{username},</if><if test="password != null">#{password},</if><if test="name != null">#{name},</if><if test="phone != null">#{phone},</if><if test="email != null">#{email},</if><if test="avatar != null">#{avatar},</if><if test="role != null">#{role},</if></trim></insert>
删除操作
前台请求
del(id){
request.delete("/admin/"+ id).then(res=>{if(res.code ==='0'){this.$message({message:'删除成功',type:'success'});this.findBySearch();}else{this.$message({message: res.msg,type:'success'});}})},
后台
controller
/**
* 删除操作
* @param id
* @return
*/@DeleteMapping("/{id}")publicResultdelete(@PathVariableInteger id){
adminService.delete(id);returnResult.success();}
service
publicvoiddelete(Integer id){
adminMapper.deleteById(id);}
mapper
intdeleteById(Integer id);
<delete id="deleteById">
delete from admin
where id=#{id}</delete>
版权归原作者 忘忧记 所有, 如有侵权,请联系我们删除。