springboot结合vue实现增删改查及分页查询

时间:2022-03-01 03:48:05

1:首先。创建一个springboot项目,这里我使用以及构建好基本框架的脚手架,打开是这个样子:

springboot结合vue实现增删改查及分页查询

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;

springboot结合vue实现增删改查及分页查询

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>

springboot结合vue实现增删改查及分页查询

这里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> {
}

springboot结合vue实现增删改查及分页查询

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);
}

springboot结合vue实现增删改查及分页查询

springboot结合vue实现增删改查及分页查询

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));
    }
}

springboot结合vue实现增删改查及分页查询

7:编写前端界面,在static里面写index.html,测试运行

springboot结合vue实现增删改查及分页查询

springboot结合vue实现增删改查及分页查询

8:通过使用elementui引入样式

springboot结合vue实现增删改查及分页查询

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
            :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>

springboot结合vue实现增删改查及分页查询

完结撒花:

springboot结合vue实现增删改查及分页查询

到此这篇关于springboot结合vue实现增删改查及分页查询的文章就介绍到这了,更多相关springboot vue 增删改查及分页查询内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/justleavel/article/details/120389400