mybatis高级连接前端进行联调把数据存入数据库

先展示数据库设计

新建一个名为your_database_name的数据库

表名叫your_table_name

属性是 id,name,address,time

CREATE TABLE `your_table_name (
  `id` int NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `address` varchar(255) DEFAULT NULL,
  `time` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

这是新建表的语句

接下来开始后端

先是pom.xml文件依赖



        <dependencies>
            <!-- Spring Boot Starter Web for RESTful APIs -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
            <!-- MyBatis Plus Starter -->
            <dependency>
                <groupId>com.baomidou</groupId>
                <artifactId>myba  tis-plus-boot-starter</artifactId>
                <version>3.5.3</version>
            </dependency>
            <!-- MySQL Driver -->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
            </dependency>
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
            </dependency>
            <dependency>
                <groupId>com.h2database</groupId>
                <artifactId>h2</artifactId>
                <scope>runtime</scope>
            </dependency>

        </dependencies>


接下来是配置文件

server.port=8090

# ???????
spring.datasource.url=jdbc:mysql://localhost:3306/your_database_name?useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

# MyBatis Plus ??
mybatis-plus.type-aliases-package=com.example.entity
mybatis-plus.mapper-locations=classpath:mapper/*.xml
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
mybatis-plus.configuration.map-underscore-to-camel-case=true

实体类

package com.xinzhi.User;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
public class YourEntity {
    private int id;
    private String name;
    private String address;
    private String time;
}

 Mapper层

 

package com.xinzhi.Mapper;

import com.xinzhi.User.YourEntity;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface YourMapper {

    @Select("SELECT * FROM your_table_name")
    List<YourEntity> getAll();

    @Select("SELECT * FROM your_table_name WHERE id = #{id}")
    YourEntity getById(Long id);

    @Insert("INSERT INTO your_table_name(name, address, time) VALUES(#{name}, #{address}, #{time})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insert(YourEntity entity);

    @Update("UPDATE your_table_name SET name = #{name}, address = #{address}, time = #{time} WHERE id = #{id}")
    int updateById(YourEntity entity);

    @Delete("DELETE FROM your_table_name WHERE id = #{id}")
    int deleteById(Long id);
}

Service层

package com.xinzhi.service;


import com.xinzhi.Mapper.YourMapper;
import com.xinzhi.User.YourEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.util.List;


@Service
public class YourService {

    @Autowired
    private YourMapper yourMapper;

    public List<YourEntity> getAll() {
        return yourMapper.getAll();
    }

    public YourEntity getById(Long id) {
        return yourMapper.getById(id);
    }

    public boolean insert(YourEntity entity) {
        return yourMapper.insert(entity) == 1;
    }

    public boolean updateById(YourEntity entity) {
        return yourMapper.updateById(entity) == 1;
    }

    public boolean deleteById(Long id) {
        return yourMapper.deleteById(id) == 1;
    }
}

controller层

package com.xinzhi.controller;


import com.xinzhi.User.YourEntity;
import com.xinzhi.service.YourService;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;


@CrossOrigin(origins = "http://localhost:8080")
@RestController
@RequestMapping("/your_entity")
public class YourController {

    @Resource
    private YourService yourService;

    @GetMapping("/all")
    public List<YourEntity> getAllEntities() {
        return yourService.getAll();
    }

    @GetMapping("/{id}")

    public YourEntity getEntityById(@PathVariable Long id) {
        return yourService.getById(id);
    }

    @PostMapping("/add")

    public String addEntity(@RequestBody YourEntity entity) {
        boolean result = yourService.insert(entity);
        if (result) {
            return "Entity added successfully";
        } else {
            return "Failed to add entity";
        }
    }

    @PutMapping("/update")
    public String updateEntity(@RequestBody YourEntity entity) {
        boolean result = yourService.updateById(entity);
        if (result) {
            return "Entity updated successfully";
        } else {
            return "Failed to update entity";
        }
    }

    @DeleteMapping("/delete/{id}")
    public String deleteEntity(@PathVariable Long id) {
        boolean result = yourService.deleteById(id);
        if (result) {
            return "Entity deleted successfully";
        } else {
            return "Failed to delete entity";
        }
    }
}

到这里后端已经完成了

接下来写前端我用的是vue2

先下载axios 命令是:

npm i axios

接着在main.js文件中引入axios

import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
Vue.use(ElementUI);

然后就在你的vue项目中写代码 我并没有用封装所以用一个类就可以写完

html

<template>
  <div>
    <!-- 新增按钮 -->
    <el-button type="primary" @click="showDialog('add')">新增</el-button>

    <!-- 表格部分 -->
    <el-table
      :data="tableData.filter(data => !search || data.name.toLowerCase().includes(search.toLowerCase()))"
      style="width: 100%">
      <el-table-column
        label="ID"
        prop="id">
      </el-table-column>
      <el-table-column
        label="Name"
        prop="name">
      </el-table-column>
      <el-table-column
        label="Address"
        prop="address">
      </el-table-column>
      <el-table-column
        label="Date"
        prop="time">
      </el-table-column>
      <el-table-column
        align="right">
        <template slot="header" slot-scope="scope">
          <el-input
            v-model="search"
            size="mini"
            placeholder="输入关键字搜索"/>
        </template>
        <template slot-scope="scope">
          <el-button
            size="mini"
            @click="showDialog('edit', scope.row)">编辑</el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增/编辑弹窗 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="30%">
   
      <el-form ref="form" :model="formData" label-width="80px">
        <el-form-item label="Name">
          <el-input v-model="formData.name"></el-input>
        </el-form-item>
        <el-form-item label="Address">
          <el-input v-model="formData.address"></el-input>
        </el-form-item>
        <el-form-item label="Date">
          <el-date-picker type="date" placeholder="选择日期" v-model="formData.time" style="width: 100%;"></el-date-picker>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </span>
    </el-dialog>
    
  </div>
</template>

js

<script>
import axios from 'axios';

export default {
  data() {
    return {
      tableData: [],
      //el中的获取数据的表格
      search: '',
      dialogVisible: false,
      dialogTitle: '',
      formData: {
        //id自动递增所以写为空 其他三个是数据表中的数据
        id: null,
        name: '',
        address: '',
        time: ''
      }
    }
  },
  created() {
    this.getAllEntities();
  },
  methods: {
    getAllEntities() {
      axios.get('http://localhost:8080/your_entity/all')
        .then(response => {
          this.tableData = response.data;
        })
        .catch(error => {
          console.error('失败', error);
        });
    },
    showDialog(type, data = null) {
      if (type === 'add') {
        this.dialogTitle = '新增';
        this.formData = {
          id: null,
          name: '',
          address: '',
          time: ''
        };
      } else if (type === 'edit') {
        this.dialogTitle = '编辑'; 
        this.formData = { ...data };
      }
      this.dialogVisible = true;
    },
    handleSubmit() {
      if (this.formData.id) {
        // 编辑
        axios.put('http://localhost:8080/your_entity/update', this.formData)
          .then(response => {
            console.log('成功');
            this.getAllEntities(); // 更新成功后重新获取数据刷新页面
            this.dialogVisible = false;
          })
          .catch(error => {
            console.error('失败', error);
          });
      } else {
        // 新增
        axios.post('http://localhost:8080/your_entity/add', this.formData)
          .then(response => {
            console.log('成功');
            this.getAllEntities(); // 添加成功后重新获取数据刷新页面
            this.dialogVisible = false;
          })
          .catch(error => {
            console.error('失败', error);
          });
      }
    },
    handleDelete(id) {
      axios.delete(`http://localhost:8080/your_entity/delete/${id}`)
        .then(response => {
          console.log('成功');
          this.getAllEntities(); // 删除成功后重新获取数据刷新页面
        })
        .catch(error => {
          console.error('失败', error);
        });
    }
  }
}
</script>

完整的一个项目就完成了

  • 22
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值