SpringBoot CRUD 简易模板后端
以单表为例。
数据库表:
sp_system_config
实体类:
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import cn.afterturn.easypoi.excel.annotation.Excel;
import lombok.Getter;
import lombok.Setter;
@JsonInclude(Include.NON_NULL)
@TableName("sp_system_config")
@Getter
@Setter
public class SystemConfig {
@TableId(
type = IdType.AUTO
)
private Long id;
@TableField("configName")
@Excel(name = "配置名")
private String configName;
@TableField("configCName")
@Excel(name = "配置中文名")
private String configCName;
@TableField("configValue")
@Excel(name = "配置值")
private String configValue;
@Excel(name = "备注")
private String remark;
@Excel(name = "单位")
private String unit;
}
基本的控制器
@RequestMapping("/systemConfig")
@RestController
public class SystemConfigController {
@Resource
private SystemConfigService systemConfigService;
}
基本的service
@Service
public class SystemConfigService {
@Resource
private SystemConfigMapper systemConfigMapper;
}
基本的mapper接口
//实体类所在包
import cn.product.entity.SystemConfig;
import org.apache.ibatis.annotations.Param;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import java.util.List;
public interface SystemConfigMapper extends LocalBaseMapper<SystemConfig> {
}
基本的mapper xml:(注意mapper的位置)
<?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="cn.product.mapper.SystemConfigMapper">
</mapper>
功能1:分页
分页返回的工具类 PageResult
import java.util.List;
public class PageResult<T> {
//当前页数
private Long pageIndex;
//每页数据数
private Long pageSize;
//总条数
private Long totalCount;
//总页数
private Long totalPage;
//列表数据
private List<T> list;
//统计数据
private Object countData;
public Long getPageIndex() {
return pageIndex;
}
public void setPageIndex(Long pageIndex) {
this.pageIndex = pageIndex;
}
public Long getPageSize() {
return pageSize;
}
public void setPageSize(Long pageSize) {
this.pageSize = pageSize;
}
public Long getTotalCount() {
return totalCount;
}
public void setTotalCount(Long totalCount) {
this.totalCount = totalCount;
}
public Long getTotalPage() {
if(this.getTotalCount()==null || this.getTotalCount()<=0){
return 0L;
}
if(this.getTotalCount()%this.getPageSize()==0){
return this.getTotalCount()/this.getPageSize();
}else{
return this.getTotalCount()/this.getPageSize()+1;
}
}
public void setTotalPage(Long totalPage) {
this.totalPage = totalPage;
}
public List<T> getList() {
return list;
}
public void setList(List<T> list) {
this.list = list;
}
public Object getCountData() {
return countData;
}
public void setCountData(Object countData) {
this.countData = countData;
}
}
分页工具:CommonPage
public class CommonPage {
//当前页码
private Integer pageIndex = 1;
//每页显示条数
private Integer pageSize = 10;
private Long skipNum ;
public Integer getPageIndex() {
if(pageIndex==null || pageIndex<=0){
return 10;
}
return pageIndex;
}
public void setPageIndex(Integer pageIndex) {
this.pageIndex = pageIndex;
}
public Integer getPageSize() {
if(pageSize==null || pageSize<=0){
return 1;
}
return pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
public Long getSkipNum() {
return (long)(this.getPageSize()*(this.getPageIndex()-1));
}
public void setSkipNum(Long skipNum) {
this.skipNum = skipNum;
}
}
查询参数实体类:SystemConfigQueryVo
//引用上面的
import cn.product.dto.CommonPage;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class SystemConfigQueryVo extends CommonPage {
private String configName;
private String configCName;
private String configValue;
}
返回的实体类就是实体类。不用再写成VO。
分页代码 :
controller -> service -> mapper
//controller代码
@ApiOperation(value = "分页查询系统配置")
@PostMapping("/page")
@ResponseBody
public PageResult<SystemConfig> page(SystemConfigQueryVo dto) {
return systemConfigService.page(dto);
}
//service代码
public PageResult<SystemConfig> page(SystemConfigQueryVo dto) {
PageResult<SystemConfig> page = new PageResult<>();
Long count = (long) systemConfigMapper.listCount(dto).size();
page.setTotalCount(count);
page.setPageSize((long) dto.getPageSize());
page.setPageIndex((long) dto.getPageIndex());
if (count == 0) {
page.setList(new ArrayList<>());
return page;
}
//设置值
List<SystemConfig> list = systemConfigMapper.list(dto);
page.setList(list);
return page;
}
//mapper 接口代码
List<SystemConfig> listCount(@Param("dto") SystemConfigQueryVo dto);
List<SystemConfig> list(@Param("dto") SystemConfigQueryVo dto);
//mapper xml代码
<select id="listCount" resultType="cn.product.entity.SystemConfig">
select * from sp_system_config
<where>
<if test="dto.configName !=null and dto.configName != '' ">
and configName like concat( '%',#{dto.configName}, '%')
</if>
<if test="dto.configCName !=null and dto.configCName != '' ">
and configCName like concat( '%',#{dto.configCName}, '%')
</if>
<if test="dto.configValue !=null and dto.configValue != '' ">
and configValue like concat( '%',#{dto.configValue}, '%')
</if>
</where>
</select>
<select id="list" resultType="cn.product.entity.SystemConfig">
select * from sp_system_config
<where>
<if test="dto.configName !=null and dto.configName != '' ">
and configName like concat( '%',#{dto.configName}, '%')
</if>
<if test="dto.configCName !=null and dto.configCName != '' ">
and configCName like concat( '%',#{dto.configCName}, '%')
</if>
<if test="dto.configValue !=null and dto.configValue != '' ">
and configValue like concat( '%',#{dto.configValue}, '%')
</if>
</where>
limit #{dto.skipNum},#{dto.pageSize}
</select>
功能2:增加/编辑
//controller代码
@ApiOperation(value = "增加系统配置")
@PostMapping("/add")
public void add(@RequestBody SystemConfig systemConfig) {
systemConfigService.add(systemConfig);
}
@ApiOperation(value = "编辑系统配置")
@PostMapping("/update")
public void update(@RequestBody SystemConfig systemConfig) {
systemConfigService.update(systemConfig);
}
//service代码
public void add(SystemConfig systemConfig) {
if (StringUtils.isEmpty(systemConfig.getConfigName())) {
throw new BusinessException("请输入配置属性!");
}
systemConfig.setConfigName(systemConfig.getConfigName().trim());
SystemConfig oldConfig = systemConfigMapper.selectOne(Wrappers.<SystemConfig>lambdaQuery().eq(SystemConfig::getConfigName, systemConfig.getConfigName()));
if (oldConfig != null) {
throw new BusinessException("该配置已经存在!");
}
systemConfigMapper.insert(systemConfig);
}
public void update(SystemConfig systemConfig) {
if (systemConfig.getId() == null) {
throw new BusinessException("请选择配置属性进行编辑!");
}
if (StringUtils.isEmpty(systemConfig.getConfigName())) {
throw new BusinessException("请输入配置属性!");
}
systemConfig.setConfigName(systemConfig.getConfigName().trim());
SystemConfig oldConfig = systemConfigMapper.selectById(systemConfig.getId());
if (oldConfig == null) {
throw new BusinessException("该配置不存在!");
}
systemConfigMapper.update(null, Wrappers.<SystemConfig>lambdaUpdate()
.eq(SystemConfig::getId, systemConfig.getId())
.set(SystemConfig::getConfigName, systemConfig.getConfigName())
.set(SystemConfig::getConfigCName, systemConfig.getConfigCName())
.set(SystemConfig::getConfigValue, systemConfig.getConfigValue())
.set(SystemConfig::getRemark, systemConfig.getRemark())
.set(SystemConfig::getUnit, systemConfig.getUnit())
);
}
功能3:删除
//controller
@ApiOperation(value = "删除系统配置")
@GetMapping("/delete")
public void delete(Integer id) {
systemConfigService.delete(id);
}
//service
public void delete(Integer id) {
systemConfigMapper.deleteById(id);
}
功能4:导出
@RequestMapping(value = "/export", method = RequestMethod.POST)
@ApiOperation(value = "导出")
public void export(@RequestBody SystemConfigQueryVo dto, HttpServletResponse resp) throws Exception {
exportBaseInfo(resp);
dto.setPageIndex(1);
dto.setPageSize(Integer.MAX_VALUE);
//像分页那样获取信息
List<SystemConfig> list = systemconfigService.page(dto).getList();
Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(),
SystemConfig.class,
list);
workbook.write(resp.getOutputStream());
}
private static void exportBaseInfo(HttpServletResponse resp) throws UnsupportedEncodingException {
resp.setCharacterEncoding("UTF-8");
String filename = new String("系统配置".getBytes("gbk"), "iso8859-1");
resp.setHeader("Content-Disposition", "attachment; filename=\"" + filename + ".xlsx\"");
resp.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
resp.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
resp.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
resp.addHeader("Access-Control-Allow-Headers",
"Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers,token");
}
功能5: 导入:
easypoi-base 4.2.0
@PostMapping("/import")
public voidimport(@RequestParam(value = "file") MultipartFile file) {
try {
ImportParams params = new ImportParams();
params.setTitleRows(0);
params.setHeadRows(1);
List<SystemConfig> list = ExcelImportUtil.importExcel(file.getInputStream(), SystemConfig.class, params);
if (list.isEmpty()) {
throw new CustomServiceException("Excel表格中没有数据");
}
//处理导入的数据
String exceptionMsg = systemConfigService.importData(list);
if (!StringUtils.isEmpty(exceptionMsg)) {
throw new CustomServiceException("Excel表格中没有数据");
}
} catch (Exception e) {
throw new CustomServiceException(e.getMessage());
}
}