增删查后端+前端整个流程例子

增删查后端+前端整个流程(Vue+Antdesign+springboot+mybatis)

前端index.vue

<template>
  <div>
    <a-input-search
      placeholder="input search GroupId"
      enter-button
      v-model="value"
      @search="onSearch"
    />
    <a-button type="primary" @click="GroupAdd" style="float:right">
      Add MlsGroup
    </a-button>
    <a-table :columns="columns" :data-source="groupList" bordered :loading="loading" :pagination="false" >
      <template slot="action" slot-scope="record" type="question-circle-o" style="color: red">
        <span>
          <a-popconfirm
            title="Are you sure delete this mlsGroup?"
            ok-text="Yes"
            cancel-text="No"
            @confirm="GroupDelete(record.id)"
          >
            <a>Delete</a>
          </a-popconfirm>
        </span>
      </template>
    </a-table>
    <!-- add group -->
    <a-modal v-model="addVisible" title="Add MlsGroup" :closable="false" :maskClosable="false" width="400px">
      <a-form-model layout="horizontal">
        <a-form-model-item label="MlsIds">
          <a-select
            v-model="addingGroupItem"
            mode="multiple"
            :default-value="['a1', 'b2']"
            style="width: 100%"
            placeholder="Please select"
            @change="handleChange"
          >
            <a-select-option v-for="d in mlsIdList" :key="d">
              {{ d }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
      </a-form-model>
      <template slot="footer">
        <a-button key="back" @click="handleAddCancel">
          Cancel
        </a-button>
        <a-button key="submit" type="primary" @click="handleAddSubmit">
          Submit
        </a-button>
      </template>
    </a-modal>
  </div>
</template>

<script>
import { deleteMlsGroup, mlsGroupList, getMlsGroup, addMlsGroup, mlsIdList } from '@/api/gaeamgr'
const columns = [
  {
    title: 'GroupId',
    dataIndex: 'id',
    width: 110
  },
  {
    title: 'MlsIds',
    dataIndex: 'mlss',
    width: 110
  },
  {
    title: 'Create Time',
    dataIndex: 'createTime',
    width: 110
  },
  {
    title: 'Operation',
    key: 'action',
    scopedSlots: { customRender: 'action' },
    width: 120
  }
]
export default {
  name: 'GroupList',
  data () {
    return {
      mlsIdList: [],
      value: '',
      loading: false,
      columns,
      groupList: [],
      initList: [],
      addingGroupItem: [],
      addVisible: false,
      selectedItems: []
    }
  },
  methods: {
    onGroupList: function () {
      this.loading = true
      mlsGroupList().then(response => {
        if (response.code !== 0) {
          this.$message.error('load error: ' + response.error)
        }
        this.groupList = response.data
        this.groupList.forEach(function (item, index) {
          item.mlss = item.mlss.join(',')
        })
        this.initList = this.groupList
      }).finally(() => {
        this.loading = false
      })
    },
    onSearch: function (value) {
      const number = /^[0-9]*$/
      // is number
      if (number.test(value)) {
        const myNumber = Number(value)
        getMlsGroup(myNumber).then(response => {
          if (response.code !== 0) {
            this.$message.error('load error: ' + response.error)
          }
          this.groupList = []
          this.groupList = this.groupList.concat(response.data)
          this.groupList.forEach(function (item, index) {
            item.mlss = item.mlss.join(',')
          })
        })
        console.log(this.groupList)
      } else {
        this.$notification.open({
          message: 'Notification',
          description:
            'please enter a number.',
          duration: 0
        })
      }
    },
    GroupDelete: function (id) {
      this.loading = true
      deleteMlsGroup(id).then(response => {
        if (response.code !== 0) {
          this.$message.error('delete error: ' + response.error)
        }
      }).finally(() => {
        this.onGroupList()
        this.loading = false
      })
    },
    GroupAdd: function () {
      this.addVisible = true
    },
    handleAddCancel: function () {
      this.addVisible = false
    },
    // add groups
    handleAddSubmit: function () {
      if (this.addingGroupItem.length === 0) {
        this.$notification.open({
          message: 'Attention',
          description:
            'please select at least one number.',
          duration: 0
        })
      }
      addMlsGroup(this.addingGroupItem).then((response) => {
        if (response.code !== 0) {
          this.$message.error('add error: ' + response.error)
        }
        console.log(response)
      }).finally(() => {
        this.onGroupList()
        this.loading = false
        this.addVisible = false
      })
    },
    getIdList: function () {
      mlsIdList().then(response => {
        if (response.code !== 0) {
          this.$message.error('load error: ' + response.error)
        }
        this.mlsIdList = response.data
      })
    },
    handleChange: function () {
      console.log(this.addingGroupItem)
    }
  },
  watch: {
    value: function (value) {
      if (value === '') {
        this.groupList = this.initList
        this.loadMore = true
      } else {
        this.loadMore = false
      }
      return value
    }
  },
  mounted () {
    this.onGroupList()
    this.getIdList()
  }
}
</script>

<style lang="less">
.ant-input-group-wrapper{
  width: 45%;
  height: 55px;
}
</style>

配置文件router.config.js,将该页面添加到当前工程想要的位置中

// eslint-disable-next-line
import { UserLayout, BasicLayout, BlankLayout } from '@/layouts'
import { bxAnaalyse } from '@/core/icons'

const RouteView = {
  name: 'RouteView',
  render: h => h('router-view')
}

export const asyncRouterMap = [
  {
    path: '/',
    name: 'index',
    component: BasicLayout,
    meta: { title: 'menu.home' },
    redirect: '/dashboard/mlsstatus',
    children: [
      // dashboard
      {
        path: '/dashboard',
        name: 'dashboard',
        redirect: '/dashboard/mlsstatus',
        component: RouteView,
        meta: { title: 'menu.dashboard', keepAlive: true, icon: bxAnaalyse },
        children: [
          {
            path: '/dashboard/mlsstatus/:pageNo([1-9]\\d*)?',
            name: 'MlsStatus',
            component: () => import('@/views/dashboard/MlsStatus'),
            meta: { title: 'menu.dashboard.mlsstatus', keepAlive: false }
          }
        ]
      },
      // mls
      {
        path: '/mls',
        redirect: '/mls/mlslist',
        component: RouteView,
        name: 'mls',
        meta: { title: 'menu.mls', icon: 'form' },
        children: [
          {
            path: '/mls/mlslist',
            name: 'MlsList',
            component: () => import('@/views/mls/mlsList'),
            meta: { title: 'menu.mls.mlsList', keepAlive: true }
          },
          {
            path: '/mls/mlsGroup',
            name: 'MlsGroup',
            component: () => import('@/views/mls/mlsGroup'),
            meta: { title: 'menu.mls.mlsGroup', keepAlive: true }
          },
          {
            path: '/mls/mlstask/:mlsId',
            name: 'MlsTask',
            component: () => import('@/views/mls/mlsTask'),
            meta: { title: 'menu.mls.mlsTask', keepAlive: true },
            hidden: true
          },
          {
            path: '/mls/mlscontent/:mlsId/:taskId',
            name: 'MlsContent',
            component: () => import('@/views/mls/mlsContent'),
            meta: { title: 'menu.mls.mlsContent', keepAlive: true },
            hidden: true
          },
          {
            path: '/mls/mlsconfig/:mlsId',
            name: 'MlsConfig',
            component: () => import('@/views/mls/mlsConfig'),
            meta: { title: 'menu.mls.mlsConfig', keepAlive: true },
            hidden: true
          }
        ]
      },
      // system
      {
        path: '/system',
        name: 'system',
        redirect: '/system/nodeManager',
        component: RouteView,
        meta: { title: 'menu.system', icon: 'safety-certificate' },
        children: [
          {
            path: '/system/nodeManager',
            name: 'NodeManager',
            component: () => import('@/views/system/nodeManager'),
            meta: { title: 'menu.system.nodeManager', keepAlive: true }
          },
          {
            path: '/system/log',
            name: 'Log',
            component: () => import('@/views/system/log'),
            meta: { title: 'menu.system.log', keepAlive: true }
          },
          {
            path: '/system/authority',
            name: 'RoleManager',
            component: () => import('@/views/system/authority'),
            meta: { title: 'menu.system.roleManager', keepAlive: true }
          }
        ]
      }
    ]
  },
  {
    path: '*',
    hidden: true
  }
]

/**
 * 基础路由
 * @type { *[] }
 */
export const constantRouterMap = [
  {
    path: '/user',
    component: UserLayout,
    redirect: '/user/login',
    hidden: true,
    children: [
      {
        path: 'login',
        name: 'login',
        component: () => import(/* webpackChunkName: "user" */ '@/views/user/Login')
      }
    ]
  }
]

gaeamgr.js,请求

import request from '@/utils/request'

export function mlsGroupList () {
  return request({
    url: `/mlsGroups`,
    method: 'get'
  })
}

export function getMlsGroup (id) {
  return request({
    url: `/mlsGroups/${id}`,
    method: 'get'
  })
}

export function deleteMlsGroup (id) {
  return request({
    url: `/mlsGroups/${id}`,
    method: 'delete'
  })
}

export function addMlsGroup (mlss) {
  return request({
    url: `/mlsGroups`,
    method: 'post',
    data: mlss
  })
}

controller层

    @GetMapping(value = "/mlsGroups")
    @ResponseBody
    public Result<List<MlsGroupBean>> mlsGroupList() {
        Result<List<MlsGroupBean>> result = new Result<>();
        List<MlsGroupBean> groupList = mlsGroupService.getMlsGroupList();
        result.setData(groupList);
        return result;
    }

    @GetMapping(value = "/mlsGroups/{id}")
    @ResponseBody
    public Result<MlsGroupBean> getMlsGroupbyId(@PathVariable("id") long id) {
        Result<MlsGroupBean> result = new Result<>();
        MlsGroupBean mlsGroupBean = mlsGroupService.getMlsGroup(id);
        result.setData(mlsGroupBean);
        return result;
    }

    @PostMapping(value = "/mlsGroups")
    @ResponseBody
    public Result<Void> addMlsGroup(@RequestBody String[] mlss,HttpServletRequest request) {
        Result<Void> result = new Result<Void>(null);
        int status = mlsGroupService.addMlsGroup(mlss);
        if (status != 1) {
            logger.info("add mlss failed");
            result.setCode(-1);
            return result;
        }
        List<MlsGroupBean> groupList = mlsGroupService.getMlsGroupList();
        long id = groupList.get(groupList.size() - 1).getId();
        actionLogService.logAddMlsGroup((String) request.getAttribute("user"), id, StringUtils.join(mlss));
        return result;
    }

    @DeleteMapping(value = "/mlsGroups/{id}")
    @ResponseBody
    @Secured(value = "ROLE_superadmin,ROLE_admin", description = "hasAnyRole")
    public Result<Void> deleteMlsGroupbyId(@PathVariable("id") long id,HttpServletRequest request) {
        Result<Void> result = new Result<Void>(null);
        String[] mlss = mlsGroupService.getMlsGroup(id).getMlss();
        int status = mlsGroupService.deleteMlsGroupbyId(id);
        if (status != 1) {
            logger.info("delete mlsGroups failed");
            result.setCode(-1);
            return result;
        }
        actionLogService.logDeleteMlsGroup((String) request.getAttribute("user"), id, StringUtils.join(mlss));
        return result;
    }

service层

@Service
public class MlsGroupServiceImpl implements MlsGroupService {

    private static final Logger logger = LoggerFactory.getLogger(MlsGroupServiceImpl.class);

    @Autowired
    private MlsGroupDao mlsGroupDao;

    //get all mlsGroup List with deleted = 0
    public List<MlsGroupBean> getMlsGroupList() {
        List<MlsGroupBean> mlsGroupList = new LinkedList<>();
        List<MlsGroupInterBean> mlsGroupInterList = mlsGroupDao.getMlsGroupsInterList();
        for (MlsGroupInterBean mlsGroupInterBean : mlsGroupInterList) {
            MlsGroupBean mlsGroupBean = new MlsGroupBean();
            mlsGroupBean.setId(mlsGroupInterBean.getId());
            mlsGroupBean.setMlss(mlsGroupInterBean.getMlss().split(","));
            mlsGroupBean.setCreateTime(mlsGroupInterBean.getCreateTime());
            mlsGroupList.add(mlsGroupBean);
        }
        return mlsGroupList;
    }

    //get MlsGroup by id with deleted = 0
    public MlsGroupBean getMlsGroup(long id) {
        MlsGroupBean mlsGroupBean = new MlsGroupBean();
        MlsGroupInterBean mlsGroupInterBean = mlsGroupDao.mlsGroupInterBean(id);
        mlsGroupBean.setId(id);
        mlsGroupBean.setMlss(mlsGroupInterBean.getMlss().split(","));
        mlsGroupBean.setCreateTime(mlsGroupInterBean.getCreateTime());
        return mlsGroupBean;
    }

    //add MlsGroup,just input mlss
    public int addMlsGroup(String[] mlss) {
        if (mlss.length == 0) {
            logger.info("insert null to mls_group");
            return -1;
        }
        Set<String> hashSet = new HashSet<>();
        for (String s : mlss) {
            hashSet.add(s);
        }
        if (hashSet.size() != mlss.length) {
            logger.info("insert repeated mlsId to mls_group");
            return -2;
        }
        String join = Joiner.on(",").join(mlss);
        return mlsGroupDao.addMlsGroup(join);
    }

    //delete MlsGroup by Id,set deleted Id = 1
    public int deleteMlsGroupbyId(long id) {
        return mlsGroupDao.deleteMlsGroupbyId(id);
    }
}

dao层

@DataSourceMybatisBase
public interface MlsGroupDao {
    String TABLE_NAME = "mls_group";

    @Insert("insert into " + TABLE_NAME
            + " (mlss)"
            + " values (#{mlss})")
    int addMlsGroup(@Param("mlss") String mlss);

    @Update("update " + TABLE_NAME
            + " set deleted = 1 "
            + " where id = #{id}")
    int deleteMlsGroupbyId(@Param("id") long id);

    @Select("select * from " + TABLE_NAME
            + " where id = #{id} "
            + " and deleted = 0")
    MlsGroupInterBean mlsGroupInterBean(@Param("id") long id);

    @Select("select * from " + TABLE_NAME
            + " where deleted = 0")
    List<MlsGroupInterBean> getMlsGroupsInterList();

}

实体层省略

posted @ 2021-06-25 16:51  cristina95  阅读(169)  评论(0)    收藏  举报