idea前后端分离增删查改

1.实体类

package com.zking.ssm.model;

import java.io.Serializable;
import lombok.Data;

/**
 * t_order
 * @author 
 */
@Data
public class Order implements Serializable {
    /**
     * 订单编号
     */
    private Integer id;

    /**
     * 订单描述
     */
    private String orderDesc;

    /**
     * 订单金额
     */
    private Double amount;

    /**
     * 客户名称
     */
    private String custName;

    /**
     * 客户电话
     */
    private String custPhone;

    /**
     * 客户地址
     */
    private String custAddr;

    private static final long serialVersionUID = 1L;
}

2.mapper.xml

<?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.zking.ssm.mapper.OrderMapper">
  <resultMap id="BaseResultMap" type="com.zking.ssm.model.Order">
    <id column="id" jdbcType="INTEGER" property="id" />
    <result column="order_desc" jdbcType="VARCHAR" property="orderDesc" />
    <result column="amount" jdbcType="FLOAT" property="amount" />
    <result column="cust_name" jdbcType="VARCHAR" property="custName" />
    <result column="cust_phone" jdbcType="VARCHAR" property="custPhone" />
    <result column="cust_addr" jdbcType="VARCHAR" property="custAddr" />
  </resultMap>
  <sql id="Base_Column_List">
    id, order_desc, amount, cust_name, cust_phone, cust_addr
  </sql>
  <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
    select 
    <include refid="Base_Column_List" />
    from t_order
    where id = #{id,jdbcType=INTEGER}
  </select>

  <select id="listOrders" parameterType="java.lang.String" resultMap="BaseResultMap">
    select
    <include refid="Base_Column_List" />
    from t_order
    <where>
      <if test="orderDesc != null and orderDesc != ''">
        and order_desc like concat('%',#{orderDesc,jdbcType=INTEGER},'%')
      </if>
    </where>
  </select>

  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
    delete from t_order
    where id = #{id,jdbcType=INTEGER}
  </delete>
  <insert id="insert" keyColumn="id" keyProperty="id" parameterType="com.zking.ssm.model.Order" useGeneratedKeys="true">
    insert into t_order (order_desc, amount, cust_name, 
      cust_phone, cust_addr)
    values (#{orderDesc,jdbcType=VARCHAR}, #{amount,jdbcType=FLOAT}, #{custName,jdbcType=VARCHAR}, 
      #{custPhone,jdbcType=VARCHAR}, #{custAddr,jdbcType=VARCHAR})
  </insert>
  <insert id="insertSelective" keyColumn="id" keyProperty="id" parameterType="com.zking.ssm.model.Order" useGeneratedKeys="true">
    insert into t_order
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="orderDesc != null">
        order_desc,
      </if>
      <if test="amount != null">
        amount,
      </if>
      <if test="custName != null">
        cust_name,
      </if>
      <if test="custPhone != null">
        cust_phone,
      </if>
      <if test="custAddr != null">
        cust_addr,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="orderDesc != null">
        #{orderDesc,jdbcType=VARCHAR},
      </if>
      <if test="amount != null">
        #{amount,jdbcType=FLOAT},
      </if>
      <if test="custName != null">
        #{custName,jdbcType=VARCHAR},
      </if>
      <if test="custPhone != null">
        #{custPhone,jdbcType=VARCHAR},
      </if>
      <if test="custAddr != null">
        #{custAddr,jdbcType=VARCHAR},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.zking.ssm.model.Order">
    update t_order
    <set>
      <if test="orderDesc != null">
        order_desc = #{orderDesc,jdbcType=VARCHAR},
      </if>
      <if test="amount != null">
        amount = #{amount,jdbcType=FLOAT},
      </if>
      <if test="custName != null">
        cust_name = #{custName,jdbcType=VARCHAR},
      </if>
      <if test="custPhone != null">
        cust_phone = #{custPhone,jdbcType=VARCHAR},
      </if>
      <if test="custAddr != null">
        cust_addr = #{custAddr,jdbcType=VARCHAR},
      </if>
    </set>
    where id = #{id,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.zking.ssm.model.Order">
    update t_order
    set order_desc = #{orderDesc,jdbcType=VARCHAR},
      amount = #{amount,jdbcType=FLOAT},
      cust_name = #{custName,jdbcType=VARCHAR},
      cust_phone = #{custPhone,jdbcType=VARCHAR},
      cust_addr = #{custAddr,jdbcType=VARCHAR}
    where id = #{id,jdbcType=INTEGER}
  </update>
</mapper>

3.service层

package com.zking.ssm.service;

import com.zking.ssm.model.Order;
import org.apache.ibatis.annotations.Param;

import java.util.List;

/**
 * @author aq
 * @site www.xiaomage.com
 * @company xxx公司
 * @create  2022-01-10 15:02
 */
public interface IOrderService {

    List<Order> listOrders(@Param("orderDesc") String orderDesc);

    void insert(Order record);

    int deleteByPrimaryKey(@Param("id")Integer id);

    int updateByPrimaryKeySelective(Order record);

}

4.mapper

 

package com.zking.ssm.mapper;

import com.zking.ssm.model.Order;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface OrderMapper {
    int deleteByPrimaryKey(Integer id);

    int insert(Order record);

    int insertSelective(Order record);

    Order selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(Order record);

    int updateByPrimaryKey(Order record);

    List<Order> listOrders(@Param("orderDesc") String orderDesc);


}

5.实现类

package com.zking.ssm.service;

import com.zking.ssm.mapper.OrderMapper;
import com.zking.ssm.model.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class OrderService implements IOrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Override
    public List<Order> listOrders(String orderDesc) {
        return orderMapper.listOrders(orderDesc);
    }

    @Override
    public void insert(Order record) {
        orderMapper.insert(record);
    }

    @Override
    public int deleteByPrimaryKey(Integer id) {
        return orderMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int updateByPrimaryKeySelective(Order record) {
        return orderMapper.updateByPrimaryKeySelective(record);
    }

}

6.controller层

package com.zking.ssm.controller;

import com.zking.ssm.model.Order;
import com.zking.ssm.service.IOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
public class OrderController {

    @Autowired
    private IOrderService orderService;

    @GetMapping("/orders")
    public Object getOrders(String orderDesc) {
        List<Order> orders = orderService.listOrders(orderDesc);
        Map<String, Object> data = new HashMap<>();
        data.put("code", 1);
        data.put("msg", "操作成功");
        data.put("data", orders);
        return data;
    }

    @PostMapping("/insert")
    public Object insert(Order order) {
        Map<String,Object> data = new HashMap<>();
        try {
            orderService.insert(order);
            data.put("code", 1);
            data.put("msg", "操作成功");
            return  data;
        } catch (Exception e) {
            e.printStackTrace();
            data.put("code", -1);
            data.put("msg", "操作失败");
            return data;
        }
    }

    @PostMapping("/edit")
    public Object edit(Order order){
        Map<String,Object> data=new HashMap<>();
        try {
            orderService.updateByPrimaryKeySelective(order);
            data.put("code",1);
            data.put("msg","修改成功");
            return data;
        }catch (Exception e){
            e.printStackTrace();
            data.put("code",-1);
            data.put("msg","修改失败");
            return data;
        }
    }

    @PostMapping("/del")
    public Object del(int id){
        Map<String,Object> data=new HashMap<>();
        try {
            orderService.deleteByPrimaryKey(id);
            data.put("code",1);
            data.put("msg","删除成功");
            return data;
        }catch (Exception e){
            e.printStackTrace();
            data.put("code",-1);
            data.put("msg","删除失败");
            return data;
        }
    }


}

7.前端代码

<template>
  <div>

    <el-form :inline="true" class="demo-form-inline">
      <el-form-item label="订单描述">
        <el-input v-model="orderDesc"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="cha()">查询</el-button>
        <el-button type="primary" @click="add()">新增</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="tableData" stripe style="width: 100%">
      <el-table-column prop="id" label="id" width="180">
      </el-table-column>
      <el-table-column prop="orderDesc" label="订单描述" width="180">
      </el-table-column>
      <el-table-column prop="custName" label="客户">
      </el-table-column>
      <el-table-column prop="custAddr" label="地址">
      </el-table-column>
      <el-table-column prop="amount" label="金额">
      </el-table-column>
      <el-table-column prop="custPhone" label="电话">
      </el-table-column>

      <el-table-column fixed="right" label="操作" width="120">
        <template slot-scope="scope">
          <el-button @click="del(scope.$index, scope.row)" type="text">删除</el-button>
          <el-button type="text" @click="edit(scope.$index, scope.row)">修改</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="title" :visible.sync="editFormVisible" width="50%" @click="closeDialog">
      <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm">
        <el-form-item label="订单描述" prop="orderDesc">
          <el-input v-model="ruleForm.orderDesc"></el-input>
        </el-form-item>
        <el-form-item label="客户" prop="custName">
          <el-input v-model="ruleForm.custName"></el-input>
        </el-form-item>
        <el-form-item label="地址" prop="custAddr">
          <el-input v-model="ruleForm.custAddr"></el-input>
        </el-form-item>
        <el-form-item label="金额" prop="amount">
          <el-input v-model="ruleForm.amount"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="custPhone">
          <el-input v-model="ruleForm.custPhone"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm()">Submit</el-button>
          <el-button @click="resetForm()">Reset</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    data: function() {
      var checkamount = (rule, value, callback) => {
        if (value == null) {
          return callback(new Error('请输入电话'));
        }
        if (isNaN(value)) {
          return callback(new Error('请输入数字'));
        }
        return callback();
      }
      var checkphone = (rule, value, callback) => {
        if (value == null) {
          return callback(new Error('请输入电话'));
        }
        if (isNaN(value)) {
          return callback(new Error('请输入数字'));
        }
        if (value.length != 11) {
          return callback(new Error('输入正确格式'));
        }
        if (value.substr(0, 1) != 1) {
          return callback(new Error('第一位为1'));
        }
        return callback();
      }
      return {
        tableData: [],
        orderDesc: '',
        title: '',
        editFormVisible: false,
        ruleForm: {
          id: 0,
          orderDesc: '',
          custAddr: '',
          custName: '',
          amount: '',
          custPhone: '',
        },

        rules: {
          orderDesc: [{
            required: true,
            massage: '不能为空',
            trigger: 'blur'
          }],
          custName: [{
            required: true,
            massage: '不能为空',
            trigger: 'blur'
          }],
          custAddr: [{
            required: true,
            massage: '不能为空',
            trigger: 'blur'
          }],
          amount: [{
            required: true,
            massage: '不能为空',
            validator: checkamount,
            trigger: 'blur',

          }],
          custPhone: [{
            required: true,
            validator: checkphone,
            trigger: 'blur'
          }],

        }


      };
    },
    methods: {
      closeDialog() {

      },
      cha() {
        let url = this.axios.urls.LIST;
        this.axios.get(url, {
          params: {
            orderDesc: this.orderDesc
          }
        }).then(resp => {
          this.tableData = resp.data.data
          console.log(this.tableData)
        }).catch(error => {
          console.log(error)
        })
      },

      add() {
        this.clearData();
        this.title = "增加"
        this.editFormVisible = true;
      },
      edit(index, row) {
        this.clearData();
        this.title = "修改"
        this.editFormVisible = true;
        this.ruleForm.id = row.id;
        this.ruleForm.orderDesc = row.orderDesc;
        this.ruleForm.custAddr = row.custAddr;
        this.ruleForm.custName = row.custName;
        this.ruleForm.amount = row.amount;
        this.ruleForm.custPhone = row.custPhone;
      },
      clearData() {
        this.editFormVisible = false;
        this.title = "";
        this.ruleForm.id = 0;
        this.ruleForm.orderDesc = '';
        this.ruleForm.custAddr = '';
        this.ruleForm.custName = '';
        this.ruleForm.amount = '';
        this.ruleForm.custPhone = '';
      },
      submitForm() {
        var a = 0;
        this.$refs['ruleForm'].validate(valid => {
          if (valid) {
            let url = '';
            if (this.ruleForm.id == 0) {
              url = this.axios.urls.INSERT;
            } else {
              a = 1;
              url = this.axios.urls.EDIT;
            }
            this.axios.post(url, this.ruleForm).then(resp => {
              console.log(resp)
              this.cha()
              this.editFormVisible = false;
              if (a == 0) {
                this.$message({
                  message: '增加成功',
                  type: 'success'
                });
              } else {
                this.$message({
                  message: '修改成功',
                  type: 'success'
                });
              }

            }).catch(error => {})
          }
        })
      },

      resetForm() {
        this.editFormVisible = false;
      },
      del(index, row) {
        var url = this.axios.urls.DEL;
        console.log(row)
        alert(row.id)
        this.axios.post(url, {
          id: row.id
        }).then(resp => {
          this.cha()
          this.$message({
            message: '删除成功',
            type: 'success'
          });
        })

      },

    },
    created() {
      this.cha()

    }
  }
</script>

<style>
</style>

8.action.js配置路径

/**
 * 对后台请求的地址的封装,URL格式如下:
 * 模块名_实体名_操作
 */
export default {
	//服务器
	'SERVER': 'http://localhost:8080/ssm',
  'LIST':'/orders',
  'INSERT':'/insert',
  'DEL':'/del',
  'EDIT':'/edit',

	//获得请求的完整地址,用于mockjs测试时使用
	'getFullPath': k => {
		return this.SERVER + this[k];
	}
}

注意:前后端端口号不能一样

结果展示

 

以下是一个使用IDEA、Spring Boot、JPA和MySQL进行增删查改的示例: 1. 首先,创建一个Spring Boot项目并添加JPA和MySQL依赖项。 2. 创建一个实体类,例如User,使用JPA注解来映射到数据库表。 ```java @Entity @Table(name = "user") public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "name") private String name; @Column(name = "age") private Integer age; // 省略getter和setter方法 } ``` 3. 创建一个JPA Repository接口,例如UserRepository,继承自JpaRepository。 ```java public interface UserRepository extends JpaRepository<User, Long> { } ``` 4. 创建一个Controller类,例如UserController,使用@Autowired注解将UserRepository注入进来。 ```java @RestController @RequestMapping("/users") public class UserController { @Autowired private UserRepository userRepository; @GetMapping("") public List<User> getAllUsers() { return userRepository.findAll(); } @GetMapping("/{id}") public User getUserById(@PathVariable Long id) { return userRepository.findById(id).orElse(null); } @PostMapping("") public User createUser(@RequestBody User user) { return userRepository.save(user); } @PutMapping("/{id}") public User updateUser(@PathVariable Long id, @RequestBody User user) { User oldUser = userRepository.findById(id).orElse(null); if (oldUser != null) { oldUser.setName(user.getName()); oldUser.setAge(user.getAge()); return userRepository.save(oldUser); } return null; } @DeleteMapping("/{id}") public void deleteUser(@PathVariable Long id) { userRepository.deleteById(id); } } ``` 5. 在application.properties文件中配置MySQL数据库连接信息。 ``` spring.datasource.url=jdbc:mysql://localhost:3306/test spring.datasource.username=root spring.datasource.password=123456 spring.jpa.hibernate.ddl-auto=update ``` 6. 运行项目并使用Postman等工具测试增删查改接口。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值