Excel与DataBase之间的导入导出

本文介绍了一种利用ExcelUtil工具类实现Excel与数据库间数据导入导出的方法。包括前端界面设计、后端代码实现及具体功能如数据读取、写入等。支持自定义注解简化实体类配置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

目录

Excel与DataBase之间的导入导出

前段代码

Body部分

导包部分

Script部分

后端代码

Util工具层

ExcelUtil工具类

读取工具类

写入工具类

自定义注解类

Entity层 

Controller层

Service层

Mapper层

XML层


Excel与DataBase之间的导入导出

先简单写一下,具体说明之后逐渐完善。

前段代码

Body部分

<template>
    <el-col :span="4">
        <el-button type="primary" @click="addBtn" icon="el-icon-circle-plus">新增</el-button>
        <el-button type="success" @click="exportBtn" icon="el-icon-download">导出</el-button>
        <el-upload class="upload-demo" action="http://localhost:9999/mbs/client/importExcel" style="width: 5px ;margin-top: -32px;margin-left: 160px">
        <el-button size="small" type="primary">导入</el-button>
        </el-upload>
    </el-col>
</template>

导包部分

import Vue from 'vue';
import axios from 'axios';
import VueAxios from 'vue-axios';
Vue.use(VueAxios, axios);

Script部分

<script>
    importBtn() {
            var _this = this;
            axios
                .post('http://localhost:9999/mbs/client/importExcel')
                .then(function (response) {
                    _this.$message.success('导入成功!');
                    _this.load();
                })
                .catch(function (error) {
                    _this.$message.error('导入失败!');
                    console.log(error);
                });
     },
     exportBtn() {
            window.location.href = 'http://localhost:9999/mbs/client/exportExcel';
     }
</script>

后端代码

Util工具层

ExcelUtil工具类

package com.member.util;


import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.util.CellRangeAddressList;


import static org.apache.poi.ss.usermodel.CellType.STRING;

/**
 * ExcelUtil工具类
 *
 * @author 拾三先生
 * @since 2020-03-08 22:00:00
 */
/*
 * ExcelUtil工具类实现功能:
 * 导出时传入list<T>,即可实现导出为一个excel,其中每个对象T为Excel中的一条记录.
 * 导入时读取excel,得到的结果是一个list<T>.T是自己定义的对象.
 * 需要导出的实体对象只需简单配置注解就能实现灵活导出,通过注解您可以方便实现下面功能:
 * 1.实体属性配置了注解就能导出到excel中,每个属性都对应一列.
 * 2.列名称可以通过注解配置.
 * 3.导出到哪一列可以通过注解配置.
 * 4.鼠标移动到该列时提示信息可以通过注解配置.
 * 5.用注解设置只能下拉选择不能随意填写功能.
 * 6.用注解设置是否只导出标题而不导出内容,这在导出内容作为模板以供用户填写时比较实用.
 */
public class ExcelUtil<T> {

    Class<T> clazz;

    public ExcelUtil(Class<T> clazz) {
        this.clazz = clazz;
    }

    public List<T> importExcel(String sheetName, InputStream input) {
        List<T> list = new ArrayList<T>();
        try {
            HSSFWorkbook workbook = new HSSFWorkbook(input);
            HSSFSheet sheet = workbook.getSheet(sheetName);
            if (!sheetName.trim().equals("")) {
                sheet = workbook.getSheet(sheetName);// 如果指定sheet名,则取指定sheet中的内容.
            }
            if (sheet == null) {
                sheet = workbook.getSheetAt(0); // 如果传入的sheet名不存在则默认指向第1个sheet.
            }
            int rows = sheet.getPhysicalNumberOfRows();
            if (rows > 0) {// 有数据时才处理
                Field[] allFields = clazz.getDeclaredFields();// 得到类的所有field.
                Map<Integer, Field> fieldsMap = new HashMap<Integer, Field>();// 定义一个map用于存放列的序号和field.
                for (Field field : allFields) {
                    // 将有注解的field存放到map中.
                    if (field.isAnnotationPresent(ExcelVOAttribute.class)) {
                        ExcelVOAttribute attr = field
                                .getAnnotation(ExcelVOAttribute.class);
                        int col = getExcelCol(attr.column());// 获得列号
                        // System.out.println(col + "====" + field.getName());
                        field.setAccessible(true);// 设置类的私有字段属性可访问.
                        fieldsMap.put(col, field);
                    }
                }
                for (int i = 1; i < rows; i++) {// 从第2行开始取数据,默认第一行是表头.
                    HSSFRow row = sheet.getRow(i);
                    int cellNum = row.getPhysicalNumberOfCells();
                    T entity = null;
                    for (int j = 0; j < cellNum; j++) {
                        HSSFCell cell = row.getCell(j);
                        if (cell == null) {
                            continue;
                        }
                        String value = "";
                        switch (cell.getCellType()) {
                            case NUMERIC: // 数字
                                //如果为时间格式的内容
                                if (HSSFDateUtil.isCellDateFormatted(cell)) {
                                    //注:format格式 yyyy-MM-dd hh:mm:ss 中小时为12小时制,若要24小时制,则把小h变为H即可,yyyy-MM-dd HH:mm:ss
                                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                                    value = sdf.format(HSSFDateUtil.getJavaDate(cell.
                                            getNumericCellValue())).toString();
                                    break;
                                } else {
                                    value = new DecimalFormat("0").format(cell.getNumericCellValue());
                                }
                                break;
                            case STRING: // 字符串
                                value = cell.getStringCellValue();
                                break;
                            case BOOLEAN: // Boolean
                                value = cell.getBooleanCellValue() + "";
                                break;
                            case FORMULA: // 公式
                                value = cell.getCellFormula() + "";
                                break;
                            case BLANK: // 空值
                                value = "";
                                break;
                            case ERROR: // 故障
                                value = "非法字符";
                                break;
                            default:
                                value = "未知类型";
                                break;
                        }
                        System.out.println(value);
                        if (value.equals("")) {
                            continue;
                        }
                        entity = (entity == null ? clazz.newInstance() : entity);// 如果不存在实例则新建.
                        // System.out.println(cells[j].getContents());
                        Field field = fieldsMap.get(j);// 从map中得到对应列的field.
                        // 取得类型,并根据对象类型设置值.
                        Class<?> fieldType = field.getType();
                        if (String.class == fieldType) {
                            field.set(entity, String.valueOf(value));
                        } else if ((Integer.TYPE == fieldType)
                                || (Integer.class == fieldType)) {
                            field.set(entity, Integer.parseInt(value));
                        } else if ((Long.TYPE == fieldType)
                                || (Long.class == fieldType)) {
                            field.set(entity, Long.valueOf(value));
                        } else if ((Float.TYPE == fieldType)
                                || (Float.class == fieldType)) {
                            field.set(entity, Float.valueOf(value));
                        } else if ((Short.TYPE == fieldType)
                                || (Short.class == fieldType)) {
                            field.set(entity, Short.valueOf(value));
                        } else if ((Double.TYPE == fieldType)
                                || (Double.class == fieldType)) {
                            field.set(entity, Double.valueOf(value));
                        } else if (Character.TYPE == fieldType) {
                            if ((value != null) && (value.length() > 0)) {
                                field.set(entity, Character
                                        .valueOf(value.charAt(0)));
                            }
                        }
                    }
                    if (entity != null) {
                        list.add(entity);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 对list数据源将其里面的数据导入到excel表单
     *
     * @param sheetName 工作表的名称
     * @param sheetSize 每个sheet中数据的行数,此数值必须小于65536
     * @param output    java输出流
     */
    public boolean exportExcel(List<T> list, String sheetName, int sheetSize,
                               OutputStream output) {
        Field[] allFields = clazz.getDeclaredFields();// 得到所有定义字段
        List<Field> fields = new ArrayList<Field>();
        // 得到所有field并存放到一个list中.
        for (Field field : allFields) {
            if (field.isAnnotationPresent(ExcelVOAttribute.class)) {
                fields.add(field);
            }
        }
        HSSFWorkbook workbook = new HSSFWorkbook();// 产生工作薄对象
        // excel2003中每个sheet中最多有65536行,为避免产生错误所以加这个逻辑.
        if (sheetSize > 65536 || sheetSize < 1) {
            sheetSize = 65536;
        }
        double sheetNo = Math.ceil(list.size() / sheetSize);// 取出一共有多少个sheet.
        for (int index = 0; index <= sheetNo; index++) {
            HSSFSheet sheet = workbook.createSheet();// 产生工作表对象
            if (sheetNo == 0) {
                workbook.setSheetName(index, sheetName);
            } else {
                workbook.setSheetName(index, sheetName + index);// 设置工作表的名称.
            }
            HSSFRow row;
            HSSFCell cell;// 产生单元格
            row = sheet.createRow(0);// 产生一行
            // 写入各个字段的列头名称
            for (int i = 0; i < fields.size(); i++) {
                Field field = fields.get(i);
                ExcelVOAttribute attr = field
                        .getAnnotation(ExcelVOAttribute.class);
                int col = getExcelCol(attr.column());// 获得列号
                cell = row.createCell(col);// 创建列
                cell.setCellType(STRING);// 设置列中写入内容为String类型
                cell.setCellValue(attr.name());// 写入列名
                // 如果设置了提示信息则鼠标放上去提示.
                if (!attr.prompt().trim().equals("")) {
                    setHSSFPrompt(sheet, "", attr.prompt(), 1, 100, col, col);// 这里默认设了2-101列提示.
                }
                // 如果设置了combo属性则本列只能选择不能输入
                if (attr.combo().length > 0) {
                    setHSSFValidation(sheet, attr.combo(), 1, 100, col, col);// 这里默认设了2-101列只能选择不能输入.
                }
            }
            int startNo = index * sheetSize;
            int endNo = Math.min(startNo + sheetSize, list.size());
            // 写入各条记录,每条记录对应excel表中的一行
            for (int i = startNo; i < endNo; i++) {
                row = sheet.createRow(i + 1 - startNo);
                T vo = (T) list.get(i); // 得到导出对象.
                for (int j = 0; j < fields.size(); j++) {
                    Field field = fields.get(j);// 获得field.
                    field.setAccessible(true);// 设置实体类私有属性可访问
                    ExcelVOAttribute attr = field
                            .getAnnotation(ExcelVOAttribute.class);
                    try {
                        // 根据ExcelVOAttribute中设置情况决定是否导出,有些情况需要保持为空,希望用户填写这一列.
                        if (attr.isExport()) {
                            cell = row.createCell(getExcelCol(attr.column()));// 创建cell
                            cell.setCellType(STRING);
                            cell.setCellValue(field.get(vo) == null ? ""
                                    : String.valueOf(field.get(vo)));// 如果数据存在就填入,不存在填入空格.
                        }
                    } catch (IllegalArgumentException e) {
                        e.printStackTrace();
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        try {
            output.flush();
            workbook.write(output);
            output.close();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("Output is closed ");
            return false;
        }
    }

    /**
     * 将EXCEL中A,B,C,D,E列映射成0,1,2,3
     *
     * @param col
     */
    public static int getExcelCol(String col) {
        col = col.toUpperCase();
        // 从-1开始计算,字母重1开始运算。这种总数下来算数正好相同。
        int count = -1;
        char[] cs = col.toCharArray();
        for (int i = 0; i < cs.length; i++) {
            count += (cs[i] - 64) * Math.pow(26, cs.length - 1 - i);
        }
        return count;
    }

    /**
     * 设置单元格上提示
     *
     * @param sheet         要设置的sheet.
     * @param promptTitle   标题
     * @param promptContent 内容
     * @param firstRow      开始行
     * @param endRow        结束行
     * @param firstCol      开始列
     * @param endCol        结束列
     * @return 设置好的sheet.
     */
    public static HSSFSheet setHSSFPrompt(HSSFSheet sheet, String promptTitle,
                                          String promptContent, int firstRow, int endRow, int firstCol,
                                          int endCol) {
        // 构造constraint对象
        DVConstraint constraint = DVConstraint
                .createCustomFormulaConstraint("DD1");
        // 四个参数分别是:起始行、终止行、起始列、终止列
        CellRangeAddressList regions = new CellRangeAddressList(firstRow,
                endRow, firstCol, endCol);
        // 数据有效性对象
        HSSFDataValidation data_validation_view = new HSSFDataValidation(
                regions, constraint);
        data_validation_view.createPromptBox(promptTitle, promptContent);
        sheet.addValidationData(data_validation_view);
        return sheet;
    }

    /**
     * 设置某些列的值只能输入预制的数据,显示下拉框.
     *
     * @param sheet    要设置的sheet.
     * @param textlist 下拉框显示的内容
     * @param firstRow 开始行
     * @param endRow   结束行
     * @param firstCol 开始列
     * @param endCol   结束列
     * @return 设置好的sheet.
     */
    public static HSSFSheet setHSSFValidation(HSSFSheet sheet,
                                              String[] textlist, int firstRow, int endRow, int firstCol,
                                              int endCol) {
        // 加载下拉列表内容
        DVConstraint constraint = DVConstraint
                .createExplicitListConstraint(textlist);
        // 设置数据有效性加载在哪个单元格上,四个参数分别是:起始行、终止行、起始列、终止列
        CellRangeAddressList regions = new CellRangeAddressList(firstRow,
                endRow, firstCol, endCol);
        // 数据有效性对象
        HSSFDataValidation data_validation_list = new HSSFDataValidation(
                regions, constraint);
        sheet.addValidationData(data_validation_list);
        return sheet;
    }
}

读取工具类

package com.member.util;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.IOException;

/**
 * PoiRead类
 *
 * @author 拾三先生
 * @since 2020-03-08 22:00:00
 */
public class PoiRead {
    public static void main(String[] args) throws IOException {
        //获取工作簿对象
        XSSFWorkbook Workbook = new XSSFWorkbook("D:\\Poi测试\\测试信息.xlsx");
        //获取工作表
        XSSFSheet sheet = Workbook.getSheetAt(0);
        //获取行
        /*for (Row row : sheet){
            //获取单元格
            for (Cell cell : row){
                String value =cell.getStringCellValue();
                System.out.println(value);
            }
        }*/

        //开始索引 0 结束索引
        int lastRowNum = sheet.getLastRowNum();
        System.out.println(lastRowNum);
        for (int i = 0; i <= lastRowNum; i++) {
            XSSFRow row = sheet.getRow(i);
            if (row != null) {
                //
                short cellNum = row.getLastCellNum();
                for (int j = 0; j <= cellNum; j++) {
                    XSSFCell cell = row.getCell(j);
                    if (cell != null) {
                        String stringCellValue = cell.getStringCellValue();
                        System.out.println(stringCellValue);
                    }

                }
            }

        }
        //释放资源
        Workbook.close();
    }
}

写入工具类

package com.member.util;

import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * WritePoi类
 *
 * @author 拾三先生
 * @since 2020-03-08 22:00:00
 */
public class WritePoi {
    public static void main(String[] args) throws IOException {
        //创建工作簿
        XSSFWorkbook workbook = new XSSFWorkbook();
        //创建工作表
        XSSFSheet sheet = workbook.createSheet("测试表一");
        //创建行
        XSSFRow row = sheet.createRow(0);
        XSSFRow row2 = sheet.createRow(1);
        //创建单元格
        row.createCell(0).setCellValue("拾三先生");
        row.createCell(1).setCellValue("拾三先生");
        row.createCell(2).setCellValue("拾三先生");
        row2.createCell(0).setCellValue("拾三先生");
        row2.createCell(1).setCellValue("拾三先生");
        row2.createCell(2).setCellValue("拾三先生");
        //输出流
        FileOutputStream out = new FileOutputStream("D:\\Poi测试\\工作簿1.xlsx");
        workbook.write(out);
        out.flush();
        //释放资源
        out.close();
        workbook.close();
        System.out.println("写入成功");
    }
}

自定义注解类

package com.member.util;


import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 自定义注解类
 *
 * @author 拾三先生
 * @since 2020-03-08 22:00:00
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({java.lang.annotation.ElementType.FIELD})
public @interface ExcelVOAttribute {

    /**
     * 导出到Excel中的名字.
     */
    public abstract String name();

    /**
     * 配置列的名称,对应A,B,C,D....
     */
    public abstract String column();

    /**
     * 提示信息
     */
    public abstract String prompt() default "";

    /**
     * 设置只能选择不能输入的列内容.
     */
    public abstract String[] combo() default {};

    /**
     * 是否导出数据,应对需求:有时我们需要导出一份模板,这是标需题要但内容需要用户手工填写.
     */
    public abstract boolean isExport() default true;
}

Entity层 

package com.member.entity;

import com.member.util.ExcelVOAttribute;

import java.io.Serializable;

/**
 * Client实体类
 *
 * @author 拾三先生
 * @since 2020-03-08 22:00:00
 */
@Data
public class Client implements Serializable {
    private static final long serialVersionUID = -50299480580387180L;
    /**
     * 会员客户ID
     */
    @ExcelVOAttribute(name = "id", column = "A")
    private Integer id;
    /**
     * 账号
     */
    @ExcelVOAttribute(name = "用户名", column = "B")
    private String username;
    /**
     * 密码
     */
    @ExcelVOAttribute(name = "密码", column = "C")
    private String password;
    /**
     * 盐值列
     */
    @ExcelVOAttribute(name = "盐值", column = "D")
    private String pwSalt;
    /**
     * 账号状态(帐号启用状态:0->禁用;1->启用)
     */
    @ExcelVOAttribute(name = "状态", column = "E")
    private Integer status;
    /**
     * (身份证,护照,军官证,台胞证,港澳台来往内地通行证)
     */
    @ExcelVOAttribute(name = "idType", column = "F")
    private String idType;
    /**
     * 正面
     */
    @ExcelVOAttribute(name = "正面", column = "G")
    private String pathFront;
    /**
     * 反面
     */
    @ExcelVOAttribute(name = "反面", column = "H")
    private String pathReverse;
    /**
     * 客户名字
     */
    @ExcelVOAttribute(name = "客户名字", column = "I")
    private String name;
    /**
     * 联系人
     */
    private String contactName;
    /**
     * 联系电话
     */
    private String contactPhone;
    /**
     * 联系地址
     */
    private String contactAddress;
    /**
     * 驾照号
     */
    @ExcelVOAttribute(name = "驾照号", column = "J")
    private String licenseNo;
    /**
     * 性别
     */
    @ExcelVOAttribute(name = "性别", column = "K")
    private String sex;
    /**
     * 电话
     */
    @ExcelVOAttribute(name = "手机号", column = "L")
    private String phoneNum;
    /**
     * 地址
     */
    @ExcelVOAttribute(name = "地址", column = "M")
    private String address;
    /**
     * 邮箱
     */
    @ExcelVOAttribute(name = "邮箱", column = "N")
    private String email;
    /**
     * 会员级别(普通,金卡,白金,钻石)
     */
    @ExcelVOAttribute(name = "会员级别", column = "O")
    private Integer memberLevelId;
    /**
     * 账户余额
     */
    @ExcelVOAttribute(name = "账户余额", column = "P")
    private Double accountBalance;
    /**
     * 积分
     */
    private int integration;
    /**
     * 成长值
     */
    private double growth;
    /**
     * 历史积分数量
     */
    private Integer historyIntegration;
    /**
     * 微信返回ID
     */
    private Integer openId;
    /**
     * 登录验证token
     */
    private String token;
    /**
     * 头像
     */
    private String headPic;
    /**
     * 会员等级
     */
    private String levelname;


    /**
     * 在客户表中添加流水表的,金额amount相关字段,进行多表同时新增和回滚
     */
    private double amount;

}

Controller层

注:具体内容应该放在业务层的,之后再修改。

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 表格操作控制层
 *
 * @author 拾三先生
 * @since 2020-03-08 22:00:00
 */
@RestController
@RequestMapping("client")
@ApiOperation("信息导入导出类")
public class ClientController {
    
    @Resource
    private ClientService clientService;

     /**
     * 将Excel表导入到数据库表
     *
     * @return String 
     */
    @PostMapping("importExcel")
    public String importExcel(@RequestParam("file") MultipartFile file) {

        InputStream is = null;
        try {
            // @RequestParam("file") MultipartFile file 是用来接收前端传递过来的文件
            is = file.getInputStream();
            //下面是自己测试
            /*is = new FileInputStream("D:\\Poi测试\\会员测试.xls");*/
        } catch (IOException e) {
            e.printStackTrace();
        }
        ExcelUtil excelUtil = new ExcelUtil(Client.class);
        List list = excelUtil.importExcel("用户信息", is);
        int n = 0;
        for (int i = 0; i < list.size(); i++) {
            Client client = (Client) list.get(i);
            System.out.println(client);
            n = clientService.insertBy(client);
            System.out.println("i值为:" + list.get(i));
        }
        if (n > 0) {
            return "success";
        }
        return "失败";
    }
}
    /**
     * 将数据库表导出到Excel表
     *
     * @return String 
     */
    @GetMapping("exportExcel")
    public String exportExcel(HttpServletResponse response) throws IOException {
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMdd hhmmss");
        String sheetName = "用户信息";
        // 初始化数据
        List<Client> clientList = clientService.selectListClient();
        FileOutputStream out = null;
        //获取配置文件中保存对应excel文件的路径,本地也可以直接写成F:excel/testExcel
        String folderPath = ResourceBundle.getBundle("application").getString("downloadFolder") + File.separator + "testExcel";
        System.out.println(folderPath);
        //创建上传文件目录
        File folder = new File(folderPath);
        //如果文件夹不存在创建对应的文件夹
        if (!folder.exists()) {
            folder.mkdirs();
        }
        //设置文件名
        String fileName = sdf1.format(new Date()) + sheetName + ".xls";
        // String savePath = folderPath + File.separator + fileName;
        response.setHeader("content-disposition",
                "attachment;fileName=" + fileName);
       /* try {
            out = new FileOutputStream(savePath);
            *//*out = new FileOutputStream(response.getOutputStream());*//*
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }*/
        ExcelUtil<Client> util = new ExcelUtil<Client>(Client.class); // 创建工具类.
        util.exportExcel(clientList, sheetName, 65536, response.getOutputStream()); // 导出
        System.out.println("----执行完毕----------");
        // System.out.println(savePath);
        //返回文件保存全路径
        return fileName;
    }

Service层

/**
 * 表格操作服务接口
 *
 * @author 拾三先生
 * @since 2020-11-17 18:40:01
 */
public interface ClientService {

    /**
     * 查询所有用户
     */
    List<Client> selectListClient();

    /**
     * 新增用户入库
     */
    int insertBy(Client client);
}
/**
 * 表格操作实现类
 *
 * @author 拾三先生
 * @since 2020-11-17 18:40:02
 */
@Service("clientService")
public class ClientServiceImpl implements ClientService {

    @Resource
    private ClientMapper clientMapper;

    /**
     * 查询所有用户
     */
    @Override
    public List<Client> selectListClient() {
        return clientMapper.selectListClient();
    }

    /**
     * 新增用户入库
     */
    @Override
    public int insertBy(Client client) {
       return clientMapper.insertBy(client);
    }
}

Mapper层

/**
 * 表格操作数据库访问层
 *
 * @author 拾三先生
 * @since 2020-11-17 18:39:59
 */
public interface ClientMapper {

    /**
     * 查询所有用户信息
     */
    List<Client> selectListClient();

    /**
     * 新增用户入库
     */
    int insertBy(Client client);
}

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.member.mapper.ClientMapper">

    <resultMap type="com.aaa.member.entity.Client" id="ClientMap">
        <result property="id" column="id" jdbcType="INTEGER"/>
        <result property="username" column="username" jdbcType="VARCHAR"/>
        <result property="password" column="password" jdbcType="VARCHAR"/>
        <result property="pwSalt" column="pw_salt" jdbcType="VARCHAR"/>
        <result property="status" column="status" jdbcType="INTEGER"/>
        <result property="idType" column="id_type" jdbcType="VARCHAR"/>
        <result property="pathFront" column="path_front" jdbcType="VARCHAR"/>
        <result property="pathReverse" column="path_reverse" jdbcType="VARCHAR"/>
        <result property="name" column="name" jdbcType="VARCHAR"/>
        <result property="contactName" column="contact_name" jdbcType="VARCHAR"/>
        <result property="contactPhone" column="contact_phone" jdbcType="VARCHAR"/>
        <result property="contactAddress" column="contact_address" jdbcType="VARCHAR"/>
        <result property="licenseNo" column="license_no" jdbcType="VARCHAR"/>
        <result property="sex" column="sex" jdbcType="VARCHAR"/>
        <result property="phoneNum" column="phone_num" jdbcType="VARCHAR"/>
        <result property="address" column="address" jdbcType="VARCHAR"/>
        <result property="email" column="email" jdbcType="VARCHAR"/>
        <result property="memberLevelId" column="member_level_id" jdbcType="INTEGER"/>
        <result property="accountBalance" column="Account_Balance" jdbcType="DOUBLE"/>
        <result property="integration" column="integration" jdbcType="VARCHAR"/>
        <result property="growth" column="growth" jdbcType="VARCHAR"/>
        <result property="historyIntegration" column="history_integration" jdbcType="INTEGER"/>
        <result property="openId" column="open_id" jdbcType="INTEGER"/>
        <result property="token" column="token" jdbcType="VARCHAR"/>
        <result property="headPic" column="head_pic" jdbcType="VARCHAR"/>
        <result property="levelname" column="levelname" jdbcType="VARCHAR"/>
    </resultMap>

    <select id="selectListClient" resultMap="ClientMap">
         select
         id, username, password, pw_salt, status, id_type, path_front, path_reverse, name, contact_name, contact_phone,
         contact_address, license_no, sex, phone_num, address, email, member_level_id, Account_Balance, integration,
         growth, history_integration, open_id, token, head_pic
         from tb_client
    </select>

    <insert id="insertBy">
        insert into tb_client
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="username != null and username != ''">
                username,
            </if>
            <if test="password != null and password != ''">
                password,
            </if>
            <if test="pwSalt != null and pwSalt != ''">
                pw_salt,
            </if>
            <if test="status != null">
                status,
            </if>
            <if test="idType != null and idType != ''">
                id_type,
            </if>
            <if test="pathFront != null and pathFront != ''">
                path_front,
            </if>
            <if test="pathReverse != null and pathReverse != ''">
                path_reverse,
            </if>
            <if test="name != null and name != ''">
                name,
            </if>
            <if test="contactName != null and contactName != ''">
                contact_name,
            </if>
            <if test="contactPhone != null and contactPhone != ''">
                contact_phone,
            </if>
            <if test="contactAddress != null and contactAddress != ''">
                contact_address,
            </if>
            <if test="licenseNo != null and licenseNo != ''">
                license_no,
            </if>
            <if test="sex != null and sex != ''">
                sex,
            </if>
            <if test="phoneNum != null and phoneNum != ''">
                phone_num,
            </if>
            <if test="address != null and address != ''">
                address,
            </if>
            <if test="email != null and email != ''">
                email,
            </if>
            <if test="memberLevelId != null">
                member_level_id,
            </if>
            <if test="accountBalance != null">
                Account_Balance,
            </if>
            <if test="integration != null and integration != ''">
                integration,
            </if>
            <if test="growth != null and growth != ''">
                growth,
            </if>
            <if test="historyIntegration != null and historyIntegration != ''">
                history_integration,
            </if>
            <if test="openId != null">
                open_id,
            </if>
            <if test="token != null and token != ''">
                token,
            </if>
            <if test="headPic != null and headPic != ''">
                head_pic,
            </if>
        </trim>
        values
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="username != null and username != ''">
                #{username,jdbcType=VARCHAR},
            </if>
            <if test="password != null and password != ''">
                #{password,jdbcType=VARCHAR},
            </if>
            <if test="pwSalt != null and pwSalt != ''">
                #{pwSalt,jdbcType=VARCHAR},
            </if>
            <if test="status != null">
                #{status,jdbcType=INTEGER},
            </if>
            <if test="idType != null and idType != ''">
                #{idType,jdbcType=VARCHAR},
            </if>
            <if test="pathFront != null and pathFront != ''">
                #{pathFront,jdbcType=VARCHAR},
            </if>
            <if test="pathReverse != null and pathReverse != ''">
                #{pathReverse,jdbcType=VARCHAR},
            </if>
            <if test="name != null and name != ''">
                #{name,jdbcType=VARCHAR},
            </if>
            <if test="contactName != null and contactName != ''">
                #{contactName,jdbcType=VARCHAR},
            </if>
            <if test="contactPhone != null and contactPhone != ''">
                #{contactPhone,jdbcType=VARCHAR},
            </if>
            <if test="contactAddress != null and contactAddress != ''">
                #{contactAddress,jdbcType=VARCHAR},
            </if>
            <if test="licenseNo != null and licenseNo != ''">
                #{licenseNo,jdbcType=VARCHAR},
            </if>
            <if test="sex != null and sex != ''">
                #{sex,jdbcType=VARCHAR},
            </if>
            <if test="phoneNum != null and phoneNum != ''">
                #{phoneNum,jdbcType=VARCHAR},
            </if>
            <if test="address != null and address != ''">
                #{address,jdbcType=VARCHAR},
            </if>
            <if test="email != null and email != ''">
                #{email,jdbcType=VARCHAR},
            </if>
            <if test="memberLevelId != null">
                #{memberLevelId,jdbcType=INTEGER},
            </if>
            <if test="accountBalance != null">
                #{accountBalance,jdbcType=DOUBLE},
            </if>
            <if test="integration != null and integration != ''">
                #{integration,jdbcType=VARCHAR},
            </if>
            <if test="growth != null and growth != ''">
                #{growth,jdbcType=VARCHAR},
            </if>
            <if test="historyIntegration != null and historyIntegration != ''">
                #{historyIntegration,jdbcType=VARCHAR},
            </if>
            <if test="openId != null">
                #{openId,jdbcType=INTEGER},
            </if>
            <if test="token != null and token != ''">
                #{token,jdbcType=VARCHAR},
            </if>
            <if test="headPic != null and headPic != ''">
                #{headPic,jdbcType=VARCHAR},
            </if>
        </trim>
    </insert>

</mapper>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值