提交 1da34f09 编写于 作者: yubinCloud's avatar yubinCloud

7-3 完成电子书分类的增删改查

上级 6ac36e11
package io.github.yubincloud.fairywiki.controller;
import io.github.yubincloud.fairywiki.dto.req.CategoryQueryReqDto;
import io.github.yubincloud.fairywiki.dto.req.CategorySaveReqDto;
import io.github.yubincloud.fairywiki.dto.resp.CategoryQueryRespDto;
import io.github.yubincloud.fairywiki.dto.resp.ErrorCode;
import io.github.yubincloud.fairywiki.dto.resp.PageRespDto;
import io.github.yubincloud.fairywiki.dto.resp.RestfulModel;
import io.github.yubincloud.fairywiki.service.CategoryService;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.validation.Valid;
@RestController
@RequestMapping("/category")
public class CategoryController {
@Resource
private CategoryService categoryService;
/**
* 对 category 进行查询的接口
* @param categoryQueryReqDto 查询条件的参数
* @return 查询到的所有category
*/
@GetMapping("/query")
public RestfulModel<PageRespDto<CategoryQueryRespDto>> queryCategorys(@Valid CategoryQueryReqDto categoryQueryReqDto) {
PageRespDto<CategoryQueryRespDto> bookList = categoryService.queryCategorys(categoryQueryReqDto);
return new RestfulModel<>(ErrorCode.SUCCESS, "", bookList);
}
/**
* 根据请求的参数保存一个 category,若id非空则为更新,否则为新增
*/
@PostMapping("/save")
public RestfulModel<Integer> saveCategory(@RequestBody @Valid CategorySaveReqDto categorySaveReqDto) {
categoryService.save(categorySaveReqDto);
return new RestfulModel<>(ErrorCode.SUCCESS, "", 0);
}
@DeleteMapping("/delete/{categoryId}")
public RestfulModel<Integer> deleteCategory(@PathVariable Long categoryId) {
categoryService.deleteOneCategory(categoryId);
return new RestfulModel<>(ErrorCode.SUCCESS, "", 0);
}
}
package io.github.yubincloud.fairywiki.dto.req;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(callSuper = true)
public class CategoryQueryReqDto extends PageReqDto {
}
package io.github.yubincloud.fairywiki.dto.req;
public class CategorySaveReqDto {
private Long id;
private Long parent;
private String name;
private Integer sort;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getParent() {
return parent;
}
public void setParent(Long parent) {
this.parent = parent;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getSort() {
return sort;
}
public void setSort(Integer sort) {
this.sort = sort;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", parent=").append(parent);
sb.append(", name=").append(name);
sb.append(", sort=").append(sort);
sb.append("]");
return sb.toString();
}
}
\ No newline at end of file
package io.github.yubincloud.fairywiki.dto.resp;
public class CategoryQueryRespDto {
private Long id;
private Long parent;
private String name;
private Integer sort;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getParent() {
return parent;
}
public void setParent(Long parent) {
this.parent = parent;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getSort() {
return sort;
}
public void setSort(Integer sort) {
this.sort = sort;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", parent=").append(parent);
sb.append(", name=").append(name);
sb.append(", sort=").append(sort);
sb.append("]");
return sb.toString();
}
}
\ No newline at end of file
package io.github.yubincloud.fairywiki.service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.github.yubincloud.fairywiki.domain.Category;
import io.github.yubincloud.fairywiki.domain.CategoryExample;
import io.github.yubincloud.fairywiki.dto.req.CategoryQueryReqDto;
import io.github.yubincloud.fairywiki.dto.req.CategorySaveReqDto;
import io.github.yubincloud.fairywiki.dto.resp.CategoryQueryRespDto;
import io.github.yubincloud.fairywiki.dto.resp.PageRespDto;
import io.github.yubincloud.fairywiki.mapper.CategoryMapper;
import io.github.yubincloud.fairywiki.utils.CopyUtil;
import io.github.yubincloud.fairywiki.utils.SnowFlake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import javax.annotation.Resource;
import java.util.List;
@Service
public class CategoryService {
private static final Logger LOG = LoggerFactory.getLogger(CategoryService.class);
@Resource
private CategoryMapper categoryMapper;
@Resource
private SnowFlake snowFlake;
/**
* 根据查询条件对数据库中的 category 进行查询并返回查询到的 category
*/
public PageRespDto<CategoryQueryRespDto> queryCategorys(CategoryQueryReqDto reqDto) {
CategoryExample categoryExample = new CategoryExample();
CategoryExample.Criteria criteria = categoryExample.createCriteria();
PageHelper.startPage(reqDto.getPageNum(), reqDto.getPageSize());
List<Category> categoryList = categoryMapper.selectByExample(categoryExample);
PageInfo<Category> pageInfo = new PageInfo<>(categoryList);
LOG.info("总行数:{}", pageInfo.getTotal());
LOG.info("总页数:{}", pageInfo.getPages());
// 列表复制
List<CategoryQueryRespDto> list = CopyUtil.copyList(categoryList, CategoryQueryRespDto.class);
PageRespDto<CategoryQueryRespDto> pageRespDto = new PageRespDto<>();
pageRespDto.setTotal(pageInfo.getTotal());
pageRespDto.setList(list);
return pageRespDto;
}
/**
* 根据 CategorySaveReqDto 来保存一个 category 记录,若 id 为空则新增,不为空则更新
*/
public void save(CategorySaveReqDto reqDto) {
Category categoryRecord = CopyUtil.copy(reqDto, Category.class);
if (ObjectUtils.isEmpty(categoryRecord.getId())) { // 判断 id 是否为空
categoryRecord.setId(snowFlake.nextId());
categoryMapper.insertSelective(categoryRecord);
} else {
categoryMapper.updateByPrimaryKey(categoryRecord);
}
}
public void deleteOneCategory(Long categoryId) {
categoryMapper.deleteByPrimaryKey(categoryId);
}
}
......@@ -13,6 +13,9 @@
<a-menu-item key="/admin/ebook">
<router-link to="/admin/ebook">电子书管理</router-link>
</a-menu-item>
<a-menu-item key="/admin/category">
<router-link to="/admin/category">分类管理</router-link>
</a-menu-item>
<a-menu-item key="/about">
<router-link to="/about">关于我们</router-link>
</a-menu-item>
......
......@@ -2,6 +2,7 @@ import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import Home from '../views/home.vue'
import About from '../views/about.vue'
import AdminEbook from '../views/admin/admin-ebook.vue'
import AdminCategory from '../views/admin/admin-category.vue'
const routes: Array<RouteRecordRaw> = [
{
......@@ -18,6 +19,11 @@ const routes: Array<RouteRecordRaw> = [
path: '/admin/ebook',
name: 'AdminEbook',
component: AdminEbook
},
{
path: '/admin/category',
name: 'AdminCategory',
component: AdminCategory
}
]
......
<template>
<a-layout>
<a-layout-content
:style="{ background: '#fff', padding: '24px', margin: 0, minHeight: '280px' }"
>
<p>
<a-form
layout="inline"
:model="categoryQueryForm"
@finish="handleQueryFormSubmit(categoryQueryForm)"
>
<a-form-item>
<a-input v-model:value="categoryQueryForm.name" placeholder="category name">
<template #prefix><EyeOutlined style="color: rgba(0, 0, 0, 0.25)" /></template>
</a-input>
</a-form-item>
<a-form-item>
<a-button
type="primary"
html-type="submit"
size="large"
:disabled="categoryQueryForm.name === ''"
>
查询
</a-button>
</a-form-item>
<a-form-item>
<a-button type="primary" @click="add()" size="large">新增</a-button>
</a-form-item>
</a-form>
</p>
<a-table
:columns="columns"
:row-key="record => record.id"
:data-source="categorys"
:pagination="pagination"
:loading="loading"
@change="handleTableChange"
>
<template #cover="{ text: cover }">
<img v-if="cover" :src="cover" alt="avatar" />
</template>
<template v-slot:action="{ text, record }">
<a-space size="small">
<a-button type="primary" @click="edit(record)">
编辑
</a-button>
<a-popconfirm
title="确认删除?"
ok-text="Yes"
cancel-text="No"
@confirm="handleDeleteCategory(record.id)"
>
<a-button type="danger">删除</a-button>
</a-popconfirm>
</a-space>
</template>
</a-table>
</a-layout-content>
</a-layout>
<a-modal
title="分类表单"
v-model:visible="modalVisible"
:confirm-loading="modalLoading"
@ok="handleModalOk"
>
<a-form :model="category" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
<a-form-item label="名称">
<a-input v-model:value="category.name" />
</a-form-item>
<a-form-item label="父分类">
<a-input v-model:value="category.parent" />
</a-form-item>
<a-form-item label="顺序">
<a-input v-model:value="category.sort" type="textarea" />
</a-form-item>
</a-form>
</a-modal>
</template>
<script lang="ts">
import { defineComponent, onMounted, ref, UnwrapRef, reactive } from 'vue';
import axios from 'axios';
import { message } from 'ant-design-vue'
import { Tool } from "@/util/tool";
interface CategoryQueryForm {
name: string;
}
export default defineComponent({
name: 'AdminCategory',
setup() {
const categoryQueryForm: UnwrapRef<CategoryQueryForm> = reactive({
name: ''
});
const categorys = ref();
const pagination = ref({
current: 1,
pageSize: 10,
total: 0
});
const loading = ref(false);
const columns = [
{
title: '名称',
dataIndex: 'name'
},
{
title: '父分类',
key: 'parent',
dataIndex: 'parent'
},
{
title: '顺序',
dataIndex: 'sort'
},
{
title: 'Action',
key: 'action',
slots: { customRender: 'action' }
}
];
/**
* 数据查询
**/
const handleQuery = (queryParams: any) => {
loading.value = true;
axios.get("/category/query", {
params: {
pageNum: queryParams.pageNum,
pageSize: queryParams.pageSize,
name: queryParams.name,
}
}).then((response) => {
loading.value = false;
const respData = response.data;
if (respData.code == 0) {
const pageData = respData.data;
categorys.value = pageData.list;
// 重置分页按钮
pagination.value.current = queryParams.pageNum;
pagination.value.total = pageData.total;
} else {
message.error(respData.msg);
}
});
};
/**
* 根据表单提交的数据进行查询
**/
const handleQueryFormSubmit = (categoryForm: CategoryQueryForm) => {
handleQuery({
pageNum: 1,
pageSize: 4,
name: categoryForm.name,
});
};
/**
* 表格点击页码时触发
*/
const handleTableChange = (pagination: any) => {
console.log("看看自带的分页参数都有啥:", pagination);
handleQuery({
pageNum: pagination.current,
pageSize: pagination.pageSize
});
};
// -------- 表单 ---------
const category = ref({});
const modalVisible = ref(false);
const modalLoading = ref(false);
const handleModalOk = () => {
modalLoading.value = true;
axios.post("/category/save", category.value).then((response) => {
const respData = response.data;
modalLoading.value = false;
if (respData.code == 0) {
modalVisible.value = false;
} else {
message.error(respData.msg);
}
handleQuery({
page: pagination.value.current,
size: pagination.value.pageSize,
});
})
};
/**
* 编辑
*/
const edit = (record: any) => {
modalVisible.value = true;
category.value = Tool.copy(record);
};
/**
* 新增
*/
const add = () => {
modalVisible.value = true;
category.value = {};
}
/**
* 删除
*/
const handleDeleteCategory = (categoryId: string) => {
console.log(categoryId);
axios.delete("/category/delete/" + categoryId).then((response) => {
const respData = response.data;
if (respData.code == 0) {
handleQuery({
page: pagination.value.current,
size: pagination.value.pageSize,
});
}
});
}
onMounted(() => {
handleQuery({
pageNum: 1,
pageSize: pagination.value.pageSize,
});
});
return {
categoryQueryForm,
labelCol: { span: 4 },
wrapperCol: { span: 14 },
categorys,
pagination,
columns,
loading,
handleTableChange,
edit,
add,
handleDeleteCategory,
handleQueryFormSubmit,
category,
modalVisible,
modalLoading,
handleModalOk
}
}
});
</script>
<style scoped>
img {
width: 50px;
height: 50px;
}
</style>
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册