(springboot+springMvc+mybatis)SSM+vue实现增删改查(crud)

文章目录

  • 前言
    • 1、springboot版本2.2.1.RELEASE
    • 2、整体项目目录
    • 3、源码
  • 一、导入jar
  • 二、配置文件application.yml
  • 三、controller -FlightController
  • 四、service FlightService
  • 五、dao
  • 六、entity-FlightEntity
  • 七、utils- ResultData
  • 八、config-MvcConfig
  • 九、在resources,创建templates目录再创建index.html
  • 十、启动类FlightApplication
  • 十一、效果

前言

1、springboot版本2.2.1.RELEASE

2、整体项目目录

(springboot+springMvc+mybatis)SSM+vue实现增删改查(crud)_第1张图片

3、源码

码云-springboot源码

一、导入jar

 <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.1.RELEASE</version>
    </parent>
    <dependencies>
        <!--Spring SpringMVC  -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>


        </dependency>
        <!--引入thymeleaf的依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.30</version>
        </dependency>

        <!-- springboot 整合mybatis -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.1.1</version>
        </dependency>

        <!--SpringBoot热部署配置 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <!-- lombok插件导包-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

        <!--        httpcomponents-->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>4.4.13</version>
        </dependency>
        <!--        common-lang-->
    </dependencies>

数据库表

CREATE TABLE `gd_flight` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'id列',
  `flight_id` varchar(20) CHARACTER SET utf8 DEFAULT NULL COMMENT '航号',
  `company` varchar(255) CHARACTER SET utf8 DEFAULT NULL COMMENT '航空公司',
  `departure_airport` varchar(255) CHARACTER SET utf8 DEFAULT NULL COMMENT '出发机场',
  `arrive_airport` varchar(255) CHARACTER SET utf8 DEFAULT NULL COMMENT '达到机场',
  `departure_time` datetime DEFAULT NULL COMMENT '出发时间',
  `arrive_time` datetime DEFAULT NULL COMMENT '到达时间',
  `model` varchar(255) CHARACTER SET utf8 DEFAULT NULL COMMENT '机型',
  `is_delete` int(11) DEFAULT NULL COMMENT '是否隐藏0显示 1隐藏',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=29 DEFAULT CHARSET=utf8mb4;

二、配置文件application.yml

###ThymeLeaf配置
spring:
  thymeleaf:
    #prefix:指定模板所在的目录
    prefix: classpath:/templates/
    #check-tempate-location: 检查模板路径是否存在
    check-template-location: true
    #cache: 是否缓存,开发模式下设置为false,避免改了模板还要重启服务器,线上设置为true,可以提高性能。
    cache: true
    suffix:  .html
    encoding: UTF-8
    mode: HTML5
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/frame?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone = GMT
    username: root
    password: root

三、controller -FlightController

package com.oyzk.controller;

import com.oyzk.entity.FlightEntity;
import com.oyzk.service.FlightService;
import com.oyzk.utils.ResultData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author Kingkang
 * @title FlightController
 * @create 2022/12/13
 **/
@Controller
public class FlightController {

    @RequestMapping("/test")
    @ResponseBody
    public String test(){
        return "test111";
    }

    @GetMapping("/")
    public String indexPage() {
        return "index"; //返回一个index.html页面
    }

    @Autowired
    private FlightService flightService;

    /**
     * 查询所有信息
     * @param
     * @return
     */
    @PostMapping("/getAllFlight")
    @ResponseBody
    public ResultData getAllFlight(){
        List<FlightEntity> all = flightService.findAll();
        return ResultData.success(all);
    }


    /**
     * 新增
     * @param flightEntity
     * @return
     */
    @RequestMapping(value = "/saveFlight", method = RequestMethod.POST)
    @ResponseBody
    public ResultData saveFlight(@RequestBody FlightEntity flightEntity){
        if (flightEntity != null) {
            flightService.insertFlight(flightEntity);
            return ResultData.fail(200,"操作成功");
        }
        return ResultData.fail(500,"参数为空");
    }



    /**
     * 更新
     * @param flightEntity
     * @param
     * @return
     */
    @RequestMapping(value = "/toUpdateFlight", method = RequestMethod.POST)
    @ResponseBody
    public ResultData toUpdateFlight(@RequestBody FlightEntity flightEntity){
        if (flightEntity != null) {
            flightService.updateFligth(flightEntity);
            return ResultData.fail(200,"操作成功");
        }
        return ResultData.fail(500,"参数为空");
    }

    /**
     * 删除
     * @param
     * @return
     */
  //  @RequestMapping(value = "/deleteFlight", method = RequestMethod.GET)
    @GetMapping("/deleteFlight")
    @ResponseBody
    public ResultData deleteFlight(Integer id){
        if(id.equals("")){
            return ResultData.fail(500,"参数为空");
        }
        flightService.deleteByIdFligth(id);
        return ResultData.fail(200,"操作成功");
    }

}

四、service FlightService

package com.oyzk.service;

import com.oyzk.entity.FlightEntity;

import java.util.List;

/**
 * @author Kingkang
 * @title FlightService
 * @create 2022/12/13
 **/
public interface FlightService {
    List<FlightEntity> findAll();



    int insertFlight(FlightEntity flightEntity);

    int updateFligth(FlightEntity flightEntity);

    int deleteByIdFligth(int id);
}

package com.oyzk.service.impl;

import com.oyzk.dao.FlightDao;
import com.oyzk.entity.FlightEntity;
import com.oyzk.service.FlightService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author Kingkang
 * @title FlightServiceImpl
 * @create 2022/12/13
 **/
@Service
public class FlightServiceImpl implements FlightService {

    @Autowired
    private FlightDao flightDao;
    @Override
    public List<FlightEntity> findAll() {
        return flightDao.findAll();
    }

    @Override
    public int insertFlight(FlightEntity flightEntity) {
        return flightDao.insertFlight(flightEntity);
    }
    @Override
    public int updateFligth(FlightEntity flightEntity) {
        return flightDao.updateFligth(flightEntity);
    }
    @Override
    public int deleteByIdFligth(int id) {
        return flightDao.deleteByIdFligth(id);
    }
}

五、dao

package com.oyzk.dao;

import com.oyzk.entity.FlightEntity;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author Kingkang
 * @title FlightService
 * @create 2022/12/13
 **/
@Repository
public interface FlightDao {
    /**
     * 查询所有信息
     * MyBatis为我们提供了注解@Results,@Result,@ResultMap
     * 用来代替mapper文件中的<resultMap>,<result>,<select id="showAll" resultMap="id">
     * @return
     */
    @Select("select*from gd_flight")
    @Results(id="floghtResultMap", value={
            @Result(column = "id",property = "id"),
            @Result(column = "flight_id",property = "flightId"),
            @Result(column = "company",property = "company"),
            @Result(column = "departure_airport",property = "departureAirport"),
            @Result(column = "arrive_airport",property = "arriveAirport"),
            @Result(column = "departure_time",property = "departureTime"),
            @Result(column = "arrive_time",property = "arriveTime"),
            @Result(column = "model",property = "model"),
            @Result(column = "is_delete",property = "isDelete")
    }
    )
    List<FlightEntity> findAll();


    @Insert("INSERT INTO gd_flight(`flight_id`, `company`, `departure_airport`, `arrive_airport`, `departure_time`, `arrive_time`, `model`, `is_delete`) " +
            "VALUES(#{flightId},#{company},#{departureAirport},#{arriveAirport},#{departureTime},#{arriveTime},#{model},#{isDelete});")
    int insertFlight(FlightEntity flightEntity);

    @Update("UPDATE gd_flight set " +
            " company=#{company},flight_id=#{flightId}, " +
            " departure_airport=#{departureAirport},arrive_airport=#{arriveAirport}," +
            " departure_time=#{departureTime},arrive_time=#{arriveTime}," +
            " model=#{model},is_delete=#{isDelete}"+
            " where id=#{id}")
    int updateFligth(FlightEntity flightEntity);

    @Delete("delete from gd_flight where id=#{id}")
    int deleteByIdFligth(int id);
}

六、entity-FlightEntity

package com.oyzk.entity;

import lombok.Data;

/**
 * @author Kingkang
 * @title FlightEntity
 * @create 2022/12/13
 **/
@Data
public class FlightEntity {

    private int id;
    private String flightId;
    private String company;
    private String departureAirport;
    private String arriveAirport;

    private String departureTime;
    private String arriveTime;
    private String model;
    private int isDelete;
}

七、utils- ResultData

package com.oyzk.utils;

import lombok.Data;

@Data
public class ResultData<T> {
    /** 状态码 */
    private int status ;
    /** 返回的操作信息 */
    private String message ;
    /** 返回的数据信息 */
    private T data ;
    /** 记录当前操作时间 */
    private long timestamp ;

    public ResultData() {
        this.timestamp = System.currentTimeMillis();
    }

    /**统一结果返回 成功时 */
    public static <T> ResultData<T> success(T data){
        ResultData<T> resultData = new ResultData<>();
        resultData.setStatus(200);
        resultData.setMessage("操作成功");
        resultData.setData(data);
        return resultData;
    }

    /**统一结果返回 失败时 */
    public static <T> ResultData<T> fail(int code,String message){
        ResultData<T> resultData = new ResultData<>();
        resultData.setStatus(code);
        resultData.setMessage(message);
        return resultData;
    }
}

八、config-MvcConfig

package com.oyzk.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

/**
 * @author Kingkang
 * @title MvcConfig 静态资源映射
 * @create 2022/12/13
 **/
@Configuration
public class MvcConfig extends WebMvcConfigurationSupport {
    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
    }
}

九、在resources,创建templates目录再创建index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>单文件例子</title>
    <!--引入element ui的css-->
    <!-- 引入样式 -->
    <link rel="stylesheet" href="../static/element-ui/theme-chalk/index.css">

</head>
<body>
<div id="app">
    <!--el开头的是elment ui模版命令,这里增加了一个添加的按钮,el-row是独占一行 -->
    <el-row>
        <el-button type="primary" @click="handleAdd">添加</el-button>
    </el-row>
    <!--:data是渲染数据-->
    <el-table
            :data="flight"
            style="width: 100%"
            height="550">
        <el-table-column
                fixed
                prop="id"
                label="编号"
                width="150">
        </el-table-column>
        <el-table-column
                prop="flightId"
                label="航班号"
                width="120">
        </el-table-column>
        <el-table-column
                prop="company"
                label="公司"
                width="120">
        </el-table-column>
        <el-table-column
                prop="departureAirport"
                label="出发地"
                width="120">
        </el-table-column>
        <el-table-column
                prop="arriveAirport"
                label="目的地"
                width="120">
        </el-table-column>
        <el-table-column
                prop="departureTime"
                label="出发时间"
                width="120">
        </el-table-column>
        <el-table-column
                prop="arriveTime"
                label="到达时间"
                width="120">
        </el-table-column>
        <el-table-column
                prop="model"
                label="飞机类型"
                width="120">
        </el-table-column>
        <el-table-column
                prop="isDelete"
                label="是否删除"
                width="120">
        </el-table-column>
        <!--    编辑 删除按钮    -->
        <el-table-column label="操作">
            <template slot-scope="scope">
                <el-button size="mini" @click="handleEdit(scope.$index, scope.row,flight)">编辑</el-button>
                <el-button size="mini" type="danger" @click="handleDelete(scope.$index,scope.row,flight)">删除</el-button>
            </template>
        </el-table-column>
    </el-table>

    <!-- 分页
    current-page 是当前页数
    pageSize 改变时会触发 这里返回的是每页条数
    page-sizes	每页显示个数选择器的选项设置 返回的是数组 [5,10,20]
    layout 组件布局,子组件名用逗号分隔 sizes, prev, pager, next, jumper, ->, total, slot
    total 总条目数
     -->
  <!--  <div class="pagination">
        <el-pagination
                background
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="pageCode"
                :page-sizes="pageOption"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="totalaElemnts">
        </el-pagination>
    </div>-->


    <!--添加与编辑、弹出层页面-->
    <div  v-show="show">

        <el-dialog title="用户信息" :visible.sync="dialogFormVisible">

            <el-form>
                <el-form-item label="航班号" :label-width="formLabelWidth">
                    <el-input v-model="formFlight.flightId" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="公司" :label-width="formLabelWidth">
                    <el-input v-model="formFlight.company" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="出发地" :label-width="formLabelWidth">
                    <el-input v-model="formFlight.departureAirport"  autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item  label="目的地" :label-width="formLabelWidth">
                    <el-input v-model="formFlight.arriveAirport"  autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item  label="出发时间" :label-width="formLabelWidth">
                    <el-input v-model="formFlight.departureTime" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item  label="到达时间" :label-width="formLabelWidth">
                    <el-input v-model="formFlight.arriveTime" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item  label="飞机类型" :label-width="formLabelWidth">
                    <el-input v-model="formFlight.model" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item  label="是否删除" :label-width="formLabelWidth">
                    <el-input v-model="formFlight.isDelete" autocomplete="off"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false" >取 消</el-button>
                <el-button v-show="btn_show" type="primary" @click="handleUpdate">确 定</el-button>
                <el-button type="primary" v-show="btn2_show" @click="add">确定添加</el-button>
            </div>
        </el-dialog>
    </div>


</div>



</body>
<!-- import Vue before Element -->
<script src="../static/vue/dist/vue.js"></script>
<!--<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>-->
<!-- 引入组件库 -->
<script src="../static/element-ui/lib/index.js"></script>
<!--官网提供的axios在线地址-->
<script src="../static/axios/axios.min.js"></script>
<script>
    new Vue({
        el: '#app',
        data() {
            return {
                show: false,
                btn_show: false,
                btn2_show: false,
                flight: [],
            /*    pageCode: 0, //默认页
                pageSize: 10,//每页10条
                totalPage: 10 ,//总页数
                pageOption: [10, 50, 100],
                totalaElemnts: 100, //总记录数*/
                dialogFormVisible:false,
                formFlight: {
                    id: '',
                    flightId: '',
                    company: '',
                    departureAirport: '',
                    arriveAirport: '',
                    departureTime: '',
                    arriveTime: '',
                    model: '',
                    isDelete: '',
                },
                formLabelWidth: '120px'
            }
        },
        methods: {
            findByPage() {
                axios.post("http://localhost:8080/getAllFlight").then( (res) => {
                    if (res.data.status === 200)
                       // this.totalPage = res.data.totalPages //总页数
                    //this.totalaElemnts = res.data.totalElements //总记录数
                    this.flight = res.data.data;
                    console.log(res.data.message)
                }).catch((err) => {
                    console.log(err)
                })

            },
        /*    handleSizeChange(val) {
                this.findByPage(this.pageCode, val)
            },
            handleCurrentChange(val) {
                this.findByPage(val, this.pageSize)
            },*/
            /**
             * 删除
             * @param index
             * @param row
             * @param crud
             */
            handleDelete(index, row, flight) {
                var id = flight[index].id;
                axios.get("http://localhost:8080/deleteFlight?id=" + id, {
                }).then((res) =>{
                   // this.findByPage(this.pageCode, this.pageSize)
                    this.findByPage()
                }).catch((err) => {
                    console.log(err)
                })
            },
            /**
             * 编辑 之前回显数据
             * @param index
             * @param row
             * @param crud
             */
            handleEdit(index, row, filght) {

                this.show = true
                this.dialogFormVisible = true
                this.btn_show = true
                this.btn2_show = false
                this.formFlight.id = filght[index].id
                this.formFlight.flightId = filght[index].flightId
                this.formFlight.company = filght[index].company
                this.formFlight.departureAirport = filght[index].departureAirport
                this.formFlight.arriveAirport = filght[index].arriveAirport
                this.formFlight.departureTime = filght[index].departureTime
                this.formFlight.arriveTime = filght[index].arriveTime
                this.formFlight.model = filght[index].model
                this.formFlight.isDelete = filght[index].isDelete
            },

            /**
             * 编辑发送ajax请求
             */
            handleUpdate() {
                axios.post("http://localhost:8080/toUpdateFlight",{
                    id: this.formFlight.id,
                    flightId: this.formFlight.flightId,
                    company:  this.formFlight.company,
                    departureAirport: this.formFlight.departureAirport,
                    arriveAirport: this.formFlight.arriveAirport,
                    departureTime: this.formFlight.departureTime,
                    arriveTime: this.formFlight.arriveTime,
                    model: this.formFlight.model,
                    isDelete: this.formFlight.isDelete
                }).then((res) => {
                    //编辑成功后刷新页面
                    // this.findByPage(this.pageCode, this.pageSize)
                    this.findByPage()
                    //关闭遮罩层
                    this.show = false
                    this.dialogFormVisible = false
                    console.log(1, res)
                }).catch((err) => {
                    console.log(2, err)
                })
            },
            /**
             * 点击添加按钮的时候显示遮罩层,同时将编辑的按钮隐藏掉
             */
            handleAdd() {
                this.show= true
                this.dialogFormVisible = true
                //将双向绑定数据滞空
                this.formFlight.id= ''
                this.formFlight.flightId= ''
                this.formFlight.company = ''
                this.formFlight.departureAirport = ''
                this.formFlight.arriveAirport = ''
                this.formFlight.departureTime = ''
                this.formFlight.arriveTime = ''
                this.formFlight.model = ''
                this.formFlight.isDelete = ''
                //将新编辑按钮隐藏掉
                this.btn_show = false
                //将新增按钮显示 v-show 其实是display:none 和black操作
                this.btn2_show  =true
            },
            /**
             *  新增
             */
            add() {
                axios.post("http://localhost:8080/saveFlight",{
                    flightId: this.formFlight.flightId,
                    company:  this.formFlight.company ,
                    departureAirport: this.formFlight.departureAirport,
                    arriveAirport: this.formFlight.arriveAirport,
                    departureTime: this.formFlight.departureTime,
                    arriveTime: this.formFlight.arriveTime,
                    model: this.formFlight.model,
                    isDelete: this.formFlight.isDelete
                }).then((res) => {
                    //添加成功后从新计算总页数
                    this.findByPage()
                    //同时关闭遮罩层
                    this.show= true
                    this.dialogFormVisible = false

                }).catch((err) => {
                    console.log(err)
                })
            }
        },
        created() {
            this.findByPage(this.pageCode, this.pageSize)
        },
    })

</script>
</html>

十、启动类FlightApplication

package com.oyzk;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @author Kingkang
 * @title FlightApplication
 * @create 2022/12/13
 **/
@SpringBootApplication
@MapperScan("com.oyzk.dao")
public class FlightApplication {
    public static void main(String[] args) {
        SpringApplication.run(FlightApplication.class,args);
    }
}

十一、效果

(springboot+springMvc+mybatis)SSM+vue实现增删改查(crud)_第2张图片

你可能感兴趣的:(SpringMVC,springBoot,Mybatis,mybatis,spring,boot,vue.js)