vhr后端-1

springboot 2.2.1.RELEASE+mybatis+mysql
Sa

1.工程前期准备

1.pom

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <dependencies>
<!--        mybatis-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.2</version>
        </dependency>
        <!-- Sa-Token 权限认证, 在线文档:http://sa-token.dev33.cn/ -->
        <dependency>
            <groupId>cn.dev33</groupId>
            <artifactId>sa-token-spring-boot-starter</artifactId>
            <version>1.30.0</version>
        </dependency>
<!--        fastjson 处理json数据转换-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.15</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
<!--        mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
<!--        简化实体类的创建-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

2.配置文件

server.port=8081

#mysql数据库
spring.datasource.hikari.max-lifetime=120000
spring.datasource.url= jdbc:mysql://数据库地址:3306/vhr
spring.datasource.username=数据库账号
spring.datasource.password=数据库密码
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

#json时间
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=GMT+8

#mapper xml路径
mybatis.mapper-locations=classpath:mapper/*.xml

#打印sql
logging.level.com.lzp.vhrserver=debug

#sa-token登录过期时间 单位为s
sa-token.activity-timeout=3000

logging.file.name=D://lzp/log/product.log

3.配置类

4.创建出需要包

entity controller service等等

5.统一返回给前端的数据类型

成功或者失败,对返回数据统一

/**
 * @author:lzp
 * @create: 2022-06-26 09:07
 * @Description: 通用数据返回工具类
 */
public class R extends HashMap<String, Object> {
	private static final long serialVersionUID = 1L;

	public R setData(Object data) {
		put("data",data);
		return this;
	}
	//利用fastjson进行反序列化
	//public <T> T getData(TypeReference<T> typeReference) {
	//	Object data = get("data");	//默认是map
	//	String jsonString = JSON.toJSONString(data);
	//	T t = JSON.parseObject(jsonString, typeReference);
	//	return t;
	//}
	利用fastjson进行反序列化
	//public <T> T getData(String key,TypeReference<T> typeReference) {
	//	Object data = get(key);	//默认是map
	//	//转为json字符串
	//	String jsonString = JSON.toJSONString(data);
	//	//转成需要的对象
	//	T t = JSON.parseObject(jsonString, typeReference);
	//	return t;
	//}
	public static long getSerialVersionUID() {
		return serialVersionUID;
	}

	public R() {
		put("code", 0);
		put("msg", "success");
	}


	//public static R error() {
	//	return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, "未知异常,请联系管理员");
	//}
	//
	public static R error(String msg) {
		return error(500, msg);
	}
	
	public static R error(int code, String msg) {
		R r = new R();
		r.put("code", code);
		r.put("msg", msg);
		return r;
	}

	public static R ok(String msg) {
		R r = new R();
		r.put("msg", msg);
		return r;
	}
	
	public static R ok(Map<String, Object> map) {
		R r = new R();
		r.putAll(map);
		return r;
	}
	
	public static R ok() {
		return new R();
	}

	public R put(String key, Object value) {
		super.put(key, value);
		return this;
	}

    public Integer getCode() {
		return (Integer) this.get("code");
    }
}

2.sa-token使用

官网:https://sa-token.dev33.cn/doc
使用到的功能:登录拦截,权限控制
使用步骤:

1.引入依赖

2.增加配置类

拦截器 对路径进行拦截,放行登录相关的请求

@Configuration
public class SaFiterConfigure  {
    /**
     * 注册 [Sa-Token全局过滤器]
     */
    @Bean
    public SaServletFilter getSaServletFilter(HttpServletRequest servletRequest,
                                              HttpServletResponse servletResponse) {

        SaServletFilter saServletFilter = new SaServletFilter();

        saServletFilter
           // 指定 拦截路由 与 放行路由
          .addInclude("/**")
          //.addExclude("/favicon.ico")
          .addExclude("/vhr/verifyCode")
          .addExclude("/vhr/checkUsername")
          // 认证函数: 每次请求执行
          .setAuth(obj -> {
            System.out.println("---------- 进入Sa-Token全局认证 -----------");
            // 登录认证 -- 拦截所有路由,并排除/user/doLogin 用于开放登录
            SaRouter.match("/**", "/vhr/dologin", () -> StpUtil.checkLogin());
            // 更多拦截处理方式,请参考“路由拦截式鉴权”章节
          }).
          // 异常处理函数:每次认证函数发生异常时执行此函数 包括未登录时访问的不存在的路径
          setError(e -> {
            NotLoginException notLoginException = (NotLoginException) e;
            //未登录
            if(notLoginException.getType().equals(NotLoginException.NOT_TOKEN)){
                return JSON.toJSONString(R.error(ExceptionEnum.NOT_LOGIN_EXCEPTION.getCode(),
                        ExceptionEnum.NOT_LOGIN_EXCEPTION.getMsg()));
            //token过期
            }else if(notLoginException.getType().equals(NotLoginException.TOKEN_TIMEOUT)){
                StpUtil.logout();
                return JSON.toJSONString(R.error(ExceptionEnum.TOKEN_TIMEOUT_EXCEPTION.getCode(),
                        ExceptionEnum.TOKEN_TIMEOUT_EXCEPTION.getMsg()));
            //在另一台设备登录
            }else if (notLoginException.getType().equals(NotLoginException.BE_REPLACED)) {
                StpUtil.logout();
                return JSON.toJSONString(R.error(ExceptionEnum.TOKEN_REPEAD_EXCEPTION.getCode(),
                        ExceptionEnum.TOKEN_REPEAD_EXCEPTION.getMsg()));
            //被踢
            } else if (notLoginException.getType().equals(NotLoginException.KICK_OUT)) {
                StpUtil.logout();
                return JSON.toJSONString(R.error(ExceptionEnum.KICK_OUT_EXCEPTION.getCode(),
                        ExceptionEnum.KICK_OUT_EXCEPTION.getMsg()));
            //token失效
            }else if (notLoginException.getType().equals(NotLoginException.INVALID_TOKEN)) {
                StpUtil.logout();
                    return JSON.toJSONString(R.error(ExceptionEnum.TOKEN_INVALID_EXCEPTION.getCode(),
                            ExceptionEnum.TOKEN_INVALID_EXCEPTION.getMsg()));
            //其他
            } else {
                return JSON.toJSONString(R.error(ExceptionEnum.OTHER_EXCEPTION.getCode(),
                        ExceptionEnum.OTHER_EXCEPTION.getMsg()));
            }
          });
        return saServletFilter;
    }
}

这样就可以对请求进行登录拦截,对于不同的登录状态进行返回。

3.对角色进行拦截

实现StpInterface 接口 重写getRoleList方法,去数据库进行查询,获取当前id的所有角色

1.增加配置类

/**
 * @author:lzp
 * @create: 2022-06-30 09:13
 * @Description: 角色配置类
 */
@Component    // 保证此类被SpringBoot扫描,完成Sa-Token的自定义权限验证扩展
public class StpInterfaceImpl implements StpInterface {

    @Autowired
   HrService hrService;
    /**
     * 返回一个账号所拥有的权限码集合
     */
    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        // 本list仅做模拟,实际项目中要根据具体业务逻辑来查询权限
        List<String> list = new ArrayList<String>();
        list.add("101");
        list.add("user-add");
        list.add("user-delete");
        list.add("user-update");
        list.add("user-get");
        list.add("article-get");
        return list;
    }

    /**
     * 返回一个账号所拥有的角色标识集合 (权限与角色可分开校验)
     */
    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        //去数据库获取角色
        HrVo hrInfo = hrService.getHrInfo(Integer.parseInt(loginId.toString()));
        List<String> rolesZh = hrInfo.getRoles();
        return rolesZh;
    }

}

2.使用

对于需要校验角色的请求
在这里插入图片描述
也可以使用注解的方式,需要配置拦截器,这里用的过滤器拦截路径的方式,所以没有用注解

3.业务逻辑

1.登录处理

1.验证码

controller

    /**
    *@param request
    *@param resp
    *@return: void
    *@Author: lzp
    *@date: 2022/6/26 9:56
    *@Description: 生成验证码 返回给前端
    */
    @GetMapping("/verifyCode")
    public void verifyCode(HttpServletRequest request, HttpServletResponse resp) throws IOException {
        //验证码实体类
        VerificationCode code = new VerificationCode();
        //获取验证码图片
        BufferedImage image = code.getImage();
        //获取验证码内容
        String text = code.getText();
        //将内容存到session
        HttpSession session = request.getSession(true);
        session.setAttribute("verify_code", text);
        //将图片返回给前端
        VerificationCode.output(image,resp.getOutputStream());
    }

2.验证账号是否存在

controller

    /**
    *@param username
    *@return: com.lzp.vhrserver.utils.R
    *@Author: lzp
    *@date: 2022/6/26 9:47
    *@Description: 校验用户名是否存在
    */
    @RequestMapping("/checkUsername")
    public R checkUsername(String username){
        if(!hrService.checkUsername(username)){
            return R.error(ExceptionEnum.USER_NOT_EXIST.getCode(),
                    ExceptionEnum.USER_NOT_EXIST.getMsg());
        }
        return R.ok("√");
    }

service

    /**
     * @Author lzp
     * @Description:  查询用户名是否存在
     * @Date: 11:05 2022/6/28
     * @Param: [username]
     * @return: boolean
     */
    public boolean checkUsername(String username) {
        if(hrMapper.checkUsername(username)==0){
            return false;
        }
        return true;
    }

sql
就是根据输入的账号去数据库查询,如果数量为0,说明没有此账号

        <select id="checkUsername" resultType="java.lang.Integer">
                select count(1) from hr where username=#{username}
        </select>

3.验证密码

controller

    /**
    *@param hrLoginVo
    *@param httpServletRequest
    *@return: com.lzp.vhrserver.utils.R
    *@Author: lzp
    *@date: 2022/6/26 9:50
    *@Description: 登录处理
    */
    @RequestMapping("dologin")
    public R doLogin(@RequestBody HrLoginVo hrLoginVo,HttpServletRequest httpServletRequest) {
        //校验验证码
        //String verifyCode = (String) httpServletRequest.getSession().getAttribute("verify_code");
        //if(!hrLoginVo.getCode().equalsIgnoreCase(verifyCode)) {
        //    return R.error(ExceptionEnum.CODE_ERROE.getCode(),
        //            ExceptionEnum.CODE_ERROE.getMsg());
        //}

        //校验密码
        HrVo hrvo = hrService.doLogin(hrLoginVo);
        //没查到就返回密码错误
        if(hrvo==null){
            return R.error(ExceptionEnum.PASSWORD_ERROE.getCode(),
                    ExceptionEnum.PASSWORD_ERROE.getMsg());
        }
        StpUtil.login(hrvo.getId());
        return R.ok("登录成功").setData(hrvo);
    }

service

    /**
     * @Author lzp
     * @Description:  校验密码,返回用户信息 包括角色信息
     * @Date: 11:06 2022/6/28
     * @Param: [hrLoginVo]
     * @return: com.lzp.vhrserver.vo.HrVo
     */
    public HrVo doLogin(HrLoginVo hrLoginVo) {
        //根据用户名和密码去数据库查,如果查不到就说明密码不对
        HrEntity hrEntity  = hrMapper.getHrInfoByHrname(hrLoginVo.getUsername(),
                SaSecureUtil.md5(hrLoginVo.getPassword()));

        //一定要注意对象为空的判断 ,从数据库取出一条数据,从里边取值之前一定要判断改对象是否为空!!!
        if(hrEntity!=null) {
            HrVo hrVo = new HrVo();
            //获取角色 根据hrid
            List<RoleEntity> roleEntities = hrMapper.getRolesByHrId(hrEntity.getId());
            BeanUtils.copyProperties(hrEntity, hrVo);
            List<String> nameList = new ArrayList<>();
            List<String> namezHList = new ArrayList<>();
            //获取角色的英文名和中文名,前台根据英文名进行权限校验
            for (RoleEntity roleEntity : roleEntities) {
                nameList.add(roleEntity.getName());
                namezHList.add(roleEntity.getNameZh());
            }
            hrVo.setRoles(nameList);
            hrVo.setRolesZh(namezHList);
            return hrVo;
        }
        //没查到就返回空
        return null;
    }

返回的数据
包括当前的hrid和角色的中文名和英文名

{
	"msg": "登录成功",
	"code": 0,
	"data": {
		"id": 3,
		"name": null,
		"phone": null,
		"telephone": null,
		"address": null,
		"enabled": null,
		"username": null,
		"password": null,
		"userface": null,
		"remark": null,
		"roles": ["ROLE_admin"],
		"rolesZh": ["系统管理员"]
	}
}

2.个人中心

1.hr信息展示

controller
根据当前hrId查询用户信息

    /**
     *@Author: lzp
     *@Description:
     *@Date: 2022/6/27 21:29
     *@Params [hrId]
     *@return com.lzp.vhrserver.utils.R
     **/
    @GetMapping("/getHrInfo")
    public R getHrInfo(Integer hrId){
        HrVo hrInfo = hrService.getHrInfo(hrId);
        if (hrInfo!=null){
            return R.ok("").setData(hrInfo);
        }
        return R.ok("");
    }

service

    /**
     *@Author: lzp
     *@Description: 根据id获取用户信息
     *@Date: 2022/6/27 21:31
     *@Params [hrId]
     *@return com.lzp.vhrserver.vo.HrVo
     **/
    public HrVo getHrInfo(Integer hrId) {
        //根据id查询hr信息
        HrEntity hrInfo = hrMapper.getHrInfo(hrId);
        HrVo hrVo = new HrVo();
        if(StringUtils.isEmpty(hrInfo)){
            return null;
        }
        //将信息拷贝到hrvo
        BeanUtils.copyProperties(hrInfo,hrVo);
        List<String> nameList = new ArrayList<>();
        List<String> namezHList = new ArrayList<>();
        //获取角色信息
        List<RoleEntity> roleEntities = hrMapper.getRolesByHrId(hrId);
        //遍历角色信息,遍历前判断是否为空
        if(!StringUtils.isEmpty(roleEntities)){
            for(RoleEntity roleEntity:roleEntities){
                nameList.add(roleEntity.getName());
                namezHList.add(roleEntity.getNameZh());
            }
            hrVo.setRoles(nameList);
            hrVo.setRolesZh(namezHList);
        }
        return hrVo;
    }

sql
获取角色和hr信息

		
        <select id="getRolesByHrId" resultType="com.lzp.vhrserver.entity.RoleEntity">
                SELECT role.name,role.nameZh FROM hr_role JOIN role ON hr_role.`rid`=role.`id` WHERE hrid=#{HrId}
        </select>

        <select id="getHrInfo" resultType="com.lzp.vhrserver.entity.HrEntity">
                select id,name,phone,telephone,address,userface from hr where id=#{hrId};
        </select>

2.修改hr信息

controller
//这里接收参数可以用HrEntity(最好别用map。。。)

    /**
     * @Author lzp
     * @Description: 修改用户信息
     * @Date: 11:51 2022/6/28
     * @Param: [ruleForm]
     * @return: com.lzp.vhrserver.utils.R
     */
    @PostMapping("/modifyUserInfo")
    public R modifyUserInfo(@RequestBody Map<String, Object> hrInfoForm){
        hrService.modifyUserInfo(hrInfoForm);
        return R.ok("修改信息成功");
    }

service

    public void modifyUserInfo(Map<String, Object> hrInfoForm) {
        //System.out.println(hrInfoForm);
        hrMapper.modifyUserInfo(hrInfoForm);
    }

sql

        <update id="modifyUserInfo">
                update hr set
                                  name=#{hrInfoForm.name},phone=#{hrInfoForm.phone},telephone=#{hrInfoForm.telephone},address=#{hrInfoForm.address} where id=#{hrInfoForm.id}
        </update>

3.修改密码

controller

    /**
     * @Author lzp
     * @Description:  修改密码
     * @Date: 10:19 2022/6/28
     * @Param: [ruleForm]
     * @return: com.lzp.vhrserver.utils.R
     */
    @PostMapping("/modefyPassword")
    public R modefyPassword(@RequestBody Map<String, Object> ruleForm){
        if(!hrService.modefyPassword(ruleForm))
            return R.error(ExceptionEnum.PASSWORD_NOT_SAME.getCode(),ExceptionEnum.PASSWORD_NOT_SAME.getMsg());
        return R.ok("更新密码成功,请重新登录");
    }

service

    /**
     * @Author lzp
     * @Description:  修改密码
     * @Date: 11:06 2022/6/28
     * @Param: [ruleForm]
     * @return: java.lang.Boolean
     */
    public Boolean modefyPassword( Map<String, Object> ruleForm) {
        //根据hrid查询用户的密码
        String password = hrMapper.getPasswordById(ruleForm.get("hrId"));
        //和传进来的原密码进行匹配
        if(!SaSecureUtil.md5((String) ruleForm.get("oldpass")).equals(password)){
            return false;
        }
        //修改数据库密码
        hrMapper.modefyPassword(SaSecureUtil.md5((String) ruleForm.get("checkPass")),ruleForm.get("hrId"));
        return true;
    }

sql

<!--        获取原密码-->
        <select id="getPasswordById" resultType="java.lang.String">
                select password from hr where id=#{hrId}
        </select>
<!--        修改密码-->
        <update id="modefyPassword">
                update hr set password=#{checkPass} where id=#{hrId}
        </update>        

3.超级管理员的设置

1.查询所有的hr

需要有超级管理员的角色才可以查询
可能会模糊搜索查询
html

    /**
     * @Author lzp
     * @Description: 获取所有的hr
     * @Date: 16:46 2022/6/28
     * @Param: [keyword] 模糊查询的关键字
     * @return: com.lzp.vhrserver.utils.R
     */

    @GetMapping("/getHrs")
    public R getHrs(@RequestParam(required = false) String keyword){
        if(!StpUtil.hasRole("ROLE_admin")){
            return R.error(ExceptionEnum.ROLE_SMALL_EXCEPTION.getCode(),
                    ExceptionEnum.ROLE_SMALL_EXCEPTION.getMsg());
        }
        List<HrVo> hrs = this.hrService.getHrs(keyword);
        return R.ok("").setData(hrs);
    }

service

    public List<HrVo> getHrs(String keyword) {
        List<HrVo> hrs = this.hrMapper.getHrs(keyword);
        return hrs;
    }

sql

        <select id="getHrs" resultType="com.lzp.vhrserver.vo.HrVo" resultMap="hrsResultMap">
                SELECT h.*,role.nameZh
                FROM hr h
                             LEFT JOIN hr_role ro
                                       ON h.id=ro.hrid
                             LEFT JOIN role
                                       ON ro.rid=role.`id`
                                where 1=1
                                <if test="keyword!=''and keyword != null ">
                                    and h.name like   concat('%',#{keyword,jdbcType=VARCHAR},'%')
                                </if>

        </select>
<!--        结果映射 需要注意每个hr的角色信息 是一个string类型的集合,使用colection-->
        <resultMap id="hrsResultMap" type="com.lzp.vhrserver.vo.HrVo">

                <id property="id" column="id" />
                <result property="name" column="name" />
                <result property="phone" column="phone" />
                <result property="telephone" column="telephone" />
                <result property="address" column="address" />
                <result property="enabled" column="enabled" />
                <result property="remark" column="remark" />
                <result property="userface" column="userface" />
                <collection property="rolesZh" ofType="java.lang.String" javaType="list">
                        <result column="nameZh"/>
                </collection>
        </resultMap>

2.获取所有角色

修改用户角色时需要获取所有的角色
在这里插入图片描述

controller

    /**
     *@Author: lzp
     *@Description: 获取所有角色名称
     *@Date: 2022/6/28 22:01
     *@Params []
     *@return com.lzp.vhrserver.utils.R
     **/
    @GetMapping("/getRoles")
    public R getRoles(){
        List<RoleEntity> roles = this.hrService.getRoles();
        return R.ok("").setData(roles);
    }

service

    public List<RoleEntity> getRoles() {
        List<RoleEntity> roles = this.hrMapper.getRoles();
        return roles;
    }

sql

        <select id="getRoles" resultType="com.lzp.vhrserver.entity.RoleEntity">
                select id,nameZh from role
        </select>

3.修改hr角色

controller

    /**
     * @Author lzp
     * @Description:  修改某个hr的角色信息
     * @Date: 11:24 2022/6/29
     * @Param: [hrVo] hrid集合 rolesZh集合
     * @return: com.lzp.vhrserver.utils.R
     */
    @PostMapping("/modifyRoles")
    public R modifyRoles(@RequestBody HrVo hrVo){
        if(!this.hrService.modifyRoles(hrVo)){
            return R.error(ExceptionEnum.ROLE_NULL_EXCEPTION.getCode(),
                    ExceptionEnum.ROLE_NULL_EXCEPTION.getMsg());
        }
        return R.ok();
    }

service

    /**
     * @Author lzp
     * @Description:  先删除当前hr的所有角色
     * @Date: 14:38 2022/6/30
     * @Param: [hrVo]
     * @return: java.lang.Boolean
     */
    @Transactional
    public Boolean modifyRoles(HrVo hrVo) {
        //删除当前hr的所有角色
        this.hrMapper.deleteRoleByHrId(hrVo.getId());
        List<String> rolesZh = hrVo.getRolesZh();
        if(rolesZh.size()==0){
            return false;
        }
        //根据中文名获取id 前端传过来的为中文名
        List<Integer> rolesId = hrMapper.selectRolesIdByNameZh(rolesZh);
        //更新角色
        this.hrMapper.modifyRoles(hrVo.getId(),rolesId);
        return true;
    }

sql

<!--        删除当前hr的所有角色-->
        <delete id="deleteRoleByHrId">
                delete from hr_role where hrid=#{hrId}
        </delete>
<!--        根据中文名集合 查询id集合-->
        <select id="selectRolesIdByNameZh" resultType="java.lang.Integer">
                select id from role where nameZh in
                        <foreach collection="rolesZh" item="nameZh" open="(" close=")"
                                 separator=" , ">
                            #{nameZh}
                        </foreach>
        </select>       
<!--        插入前端传过来的角色-->
        <insert id="modifyRoles">
                insert into hr_role(hrid,rid)
                values
                <foreach collection ="rolesId" item="roleId" separator =",">
                        (#{hrId}, #{roleId})
                </foreach >
        </insert>         

4.修改用户使能情况

前端可以根据这个字段,对当前登录的hr进行鉴权
controller

    /**
     * @Author lzp
     * @Description: 修改hr的使能状态
     * @Date: 8:55 2022/6/29
     * @Param: [id]
     * @return: com.lzp.vhrserver.utils.R
     */
    @GetMapping ("/modifyEnabled")
    public R modifyEnabled(Integer id,Integer enabled){
        this.hrService.modifyEnabled(id, enabled);
        if(enabled==1){
            return R.ok("账号启用成功");
        }
        return R.ok("账号禁用成功");
    }

service

    public void modifyEnabled(Integer id,Integer enabled) {
        this.hrMapper.modifyEnabled(id,enabled);
    }

sql

        <update id="modifyEnabled">
                update hr set enabled=#{enabled} where id = #{id}
        </update>

5.删除hr的信息

html

    /**
     * @Author lzp
     * @Description:  删除hr信息
     * @Date: 14:56 2022/6/29
     * @Param: [hrId]
     * @return: com.lzp.vhrserver.utils.R
     */
    @GetMapping("/deleteHr")
    public R deleteHr(Integer hrId){
        this.hrService.deleteHr(hrId);
        return R.ok("删除成功");
    }

service
先删除hr的信息
再删除该hr的角色

    @Transactional
    public void deleteHr(Integer hrId) {
        this.hrMapper.deleteHr(hrId);
        this.hrMapper.deleteRoleByHrId(hrId);
    }

6.新增hr

controller

    /**
     * @Author lzp
     * @Description:  添加hr信息
     * @Date: 16:39 2022/6/29
     * @Param: [hrEntity]
     * @return: com.lzp.vhrserver.utils.R
     */
    @PostMapping("/addHrInfo")
    public R addHrInfo(@RequestBody HrEntity hrEntity){
        this.hrService.addHrInfo(hrEntity);
        return R.ok("添加成功");
    }

service

    public void addHrInfo(HrEntity hrEntity) {
        //密码加密
        String s = SaSecureUtil.md5((String) hrEntity.getPassword());
        hrEntity.setPassword(s);
        this.hrMapper.addHrInfo(hrEntity);
    }

sql

        <insert id="addHrInfo">
                insert into hr (name,phone,telephone,address,username,password)
                values(#{hrEntity.name,},#{hrEntity.phone},#{hrEntity.telephone},#{hrEntity.address},#{hrEntity.username},#{hrEntity.password})
        </insert>

4.员工资料

1.分页查询所有员工资料

controller
paramsMap中包含分页参数(每页记录数和当前页)和查询条件

    @GetMapping("/getEmps")
    public R getEmps(@RequestParam Map<String, Object> paramsMap){
        PageInfo<EmpVo> emps = employeeEntityService.getEmps(paramsMap);
        return R.ok("").setData(emps);
    }

service
先从map中获取搜索条件,如果根据部门搜索要特殊处理,因为可能是通过父节点搜索,要找出所有该节点部门的员工

    public PageInfo<EmpVo> getEmps(Map<String, Object> paramsMap) {
        //获取到搜索参数
        Object searchParam = paramsMap.get("searchParam");
        //转为json
        String s = JSON.toJSONString(searchParam);
        //进一步转化 不然parseObject会报错 syntax error, expect {, actual string, pos 0
        String parse =(String) JSON.parse(s);
        //转为对象 SearchParam
        SearchParam searchParam2 = JSON.parseObject(parse, SearchParam.class);
        //如果根据部门id查询
        if(null!=searchParam2.getDepartmentId()) {
            //判断这个id是不是父id
            Integer isParentId = this.departmentEntityMapper.isParmentId(searchParam2.getDepartmentId());
            //如果是
            if(isParentId==1){
                List<Integer> childId = findChildId(searchParam2.getDepartmentId(),new ArrayList<>());
                searchParam2.setChildId(childId);
                //如果是父id就不需要根据当前的部门id查询了,需要根据最后一级子id
                searchParam2.setDepartmentId(0);
            }
        }
        //分页查询
        PageHelper.startPage(paramsMap);
        PageInfo<EmpVo> employeesPageInfo =
                new PageInfo<>(employeeEntityMapper.getEmps(searchParam2));
        return employeesPageInfo;
    }
    //获取到父id的所有最后一级的子id
    public List<Integer> findChildId(Integer parentId,List <Integer> idList){
        //找到子id
        List<Integer> childId = this.departmentEntityMapper.findChildId(parentId);
        //如果没有子id了,就说明是最后一级了,把它存起来
        if(childId.size()==0){
            idList.add(parentId);
        }else {
            //遍历子id
            childId.forEach((item) -> {
                List<Integer> childId1 = findChildId(item,idList);
            });
        }
        return idList;
    }    

查询参数类
在这里插入图片描述

sql
关联查询根据id查询出部门名字等名称参数,然后判断条件存在的话匹配条件,注意名字的like查询和时间段查询语法,返回需要映射map,因为查询了其他对象

    <select id="getEmps" resultType="com.lzp.vhrserver.vo.EmpVo" resultMap="EmpVoMap">
        select e.*,
            n.id as 'nationId',n.name as 'nationName',
            p.id as 'politicId',p.name as 'politicName',
            d.id as 'departmentId', d.name as 'departmentName' ,
            j.id as 'joblevelId',j.name as 'joblevelName' ,
            po.id as 'posId' ,po.name as 'posName'
            from employee e
            left join nation n on e.nationId=n.id
            left join politicsstatus p on e.politicId=p.id
            left join department d on e.departmentId=d.id
            left join joblevel j on e.jobLevelId=j.id
            left join position po on e.posId=po.id where 1=1

            <if test="searchParam.employeeName!=''and searchParam.employeeName != null ">
                and e.name like concat('%',#{searchParam.employeeName,jdbcType=VARCHAR},'%')
            </if>

            <if test="searchParam.departmentId>0 ">
                and e.departmentId =#{searchParam.departmentId}
            </if>

            <if test="searchParam.politicId>0 ">
                and e.politicId = #{searchParam.politicId}
            </if>

            <if test="searchParam.nationId>0 ">
                and e.nationId = #{searchParam.nationId}
            </if>

            <if test="searchParam.posId>0 ">
                and e.posId = #{searchParam.posId}
            </if>

            <if test="searchParam.jobLevelId>0 ">
                and e.jobLevelId = #{searchParam.jobLevelId}
            </if>

            <if test="searchParam.engageForm!='' and searchParam.engageForm != null ">
                and e.engageForm = #{searchParam.engageForm}
            </if>

            <if test=" searchParam.start != null and searchParam.start!='' ">
                and date_format(beginDate,'%Y-%m-%d') &gt;= str_to_date(#{searchParam.start},'%Y-%m-%d')
            </if>
            <if test=" searchParam.end != null and searchParam.end!='' ">
                and date_format(beginDate,'%Y-%m-%d') &lt;= str_to_date(#{searchParam.end},'%Y-%m-%d')
            </if>
            <if test="searchParam.childId!=null and searchParam.childId.size()>0">
                and departmentId in
                <foreach collection="searchParam.childId" item="item" open="(" close=")" separator=",">
                    #{item}
                </foreach>
            </if>
            <if test="searchParam.workState!='' and searchParam.workState != null ">
                and e.workState = #{searchParam.workState}
            </if>

    </select>
    <resultMap id="EmpVoMap" type="com.lzp.vhrserver.vo.EmpVo">
            <id property="id" column="id" jdbcType="INTEGER"/>
            <result property="name" column="name" jdbcType="VARCHAR"/>
            <result property="gender" column="gender" jdbcType="CHAR"/>
            <result property="birthday" column="birthday" jdbcType="DATE"/>
            <result property="idCard" column="idCard" jdbcType="CHAR"/>
            <result property="wedlock" column="wedlock" jdbcType="OTHER"/>
            <result property="nationId" column="nationId" jdbcType="INTEGER"/>
            <result property="nativePlace" column="nativePlace" jdbcType="VARCHAR"/>
            <result property="politicId" column="politicId" jdbcType="INTEGER"/>
            <result property="email" column="email" jdbcType="VARCHAR"/>
            <result property="phone" column="phone" jdbcType="VARCHAR"/>
            <result property="address" column="address" jdbcType="VARCHAR"/>
            <result property="departmentId" column="departmentId" jdbcType="INTEGER"/>
            <result property="jobLevelId" column="jobLevelId" jdbcType="INTEGER"/>
            <result property="posId" column="posId" jdbcType="INTEGER"/>
            <result property="engageForm" column="engageForm" jdbcType="VARCHAR"/>
            <result property="tiptopDegree" column="tiptopDegree" jdbcType="OTHER"/>
            <result property="specialty" column="specialty" jdbcType="VARCHAR"/>
            <result property="school" column="school" jdbcType="VARCHAR"/>
            <result property="beginDate" column="beginDate" jdbcType="DATE"/>
            <result property="workState" column="workState" jdbcType="OTHER"/>
            <result property="workId" column="workID" jdbcType="CHAR"/>
            <result property="contractTerm" column="contractTerm" jdbcType="DOUBLE"/>
            <result property="conversionTime" column="conversionTime" jdbcType="DATE"/>
            <result property="notWorkDate" column="notWorkDate" jdbcType="DATE"/>
            <result property="beginContract" column="beginContract" jdbcType="DATE"/>
            <result property="endContract" column="endContract" jdbcType="DATE"/>
            <result property="workAge" column="workAge" jdbcType="INTEGER"/>
        <association property="joblevelEntity"  javaType="com.lzp.vhrserver.entity.JoblevelEntity">
            <id property="id" column="joblevelId"></id>
            <result property="name" column="joblevelName"></result>
        </association>
        <association property="departmentEntity"  javaType="com.lzp.vhrserver.entity.DepartmentEntity">
            <id property="id" column="departmentId"></id>
            <result property="name" column="departmentName"></result>
        </association>
        <association property="positionEntity"  javaType="com.lzp.vhrserver.entity.PositionEntity">
            <id property="id" column="posId"></id>
            <result property="name" column="posName"></result>
        </association>
        <association property="politicsstatusEntity"  javaType="com.lzp.vhrserver.entity.PoliticsstatusEntity">
            <id property="id" column="politicId"></id>
            <result property="name" column="politicName"></result>
        </association>
        <association property="nationEntity"  javaType="com.lzp.vhrserver.entity.NationEntity">
            <id property="id" column="nationId"></id>
            <result property="name" column="nationName"></result>
        </association>
    </resultMap>    

增强类
在这里插入图片描述

2.编辑用户信息

此处使用putmapping
controller

    /**
     * @Author lzp
     * @Description:  更新员工信息
     * @Date: 15:35 2022/7/3
     * @Param: [employeeEntity]
     * @return: com.lzp.vhrserver.utils.R
     */
    @PutMapping("/updateEmp")
    public R updateEmp(@RequestBody EmployeeEntity employeeEntity){
        if(this.employeeEntityService.updateEmp(employeeEntity)){
            return R.ok("修改成功");
        }
        return R.error(3,"修改失败");
    }

service
同样返回作用的条数,如果不是1,说明修改失败

    public Boolean updateEmp(EmployeeEntity employeeEntity) {
        Integer integer = this.employeeEntityMapper.updateEmp(employeeEntity);
        if(integer==1){
            return true;
        }
        return false;
    }

sql
这里判断似乎没有必要,因为传过来是员工对象,每一项都有数据—,暂时未想到办法

    <update id="updateEmp" parameterType="com.lzp.vhrserver.entity.EmployeeEntity">
        update employee
        <set>
            <if test="name != null">
                name = #{name,jdbcType=VARCHAR},
            </if>
            <if test="gender != null">
                gender = #{gender,jdbcType=CHAR},
            </if>
            <if test="birthday != null">
                birthday = #{birthday,jdbcType=DATE},
            </if>
            <if test="idCard != null">
                idCard = #{idCard,jdbcType=CHAR},
            </if>
            <if test="wedlock != null">
                wedlock = #{wedlock,jdbcType=CHAR},
            </if>
            <if test="nationId != null">
                nationId = #{nationId,jdbcType=INTEGER},
            </if>
            <if test="nativePlace != null">
                nativePlace = #{nativePlace,jdbcType=VARCHAR},
            </if>
            <if test="politicId != null">
                politicId = #{politicId,jdbcType=INTEGER},
            </if>
            <if test="email != null">
                email = #{email,jdbcType=VARCHAR},
            </if>
            <if test="phone != null">
                phone = #{phone,jdbcType=VARCHAR},
            </if>
            <if test="address != null">
                address = #{address,jdbcType=VARCHAR},
            </if>
            <if test="departmentId != null">
                departmentId = #{departmentId,jdbcType=INTEGER},
            </if>
            <if test="jobLevelId != null">
                jobLevelId = #{jobLevelId,jdbcType=INTEGER},
            </if>
            <if test="posId != null">
                posId = #{posId,jdbcType=INTEGER},
            </if>
            <if test="engageForm != null">
                engageForm = #{engageForm,jdbcType=VARCHAR},
            </if>
            <if test="tiptopDegree != null">
                tiptopDegree = #{tiptopDegree,jdbcType=CHAR},
            </if>
            <if test="specialty != null">
                specialty = #{specialty,jdbcType=VARCHAR},
            </if>
            <if test="school != null">
                school = #{school,jdbcType=VARCHAR},
            </if>
            <if test="beginDate != null">
                beginDate = #{beginDate,jdbcType=DATE},
            </if>
            <if test="workState != null">
                workState = #{workState,jdbcType=CHAR},
            </if>
            <if test="workId != null">
                workID = #{workId,jdbcType=CHAR},
            </if>
            <if test="contractTerm != null">
                contractTerm = #{contractTerm,jdbcType=DOUBLE},
            </if>
            <if test="conversionTime != null">
                conversionTime = #{conversionTime,jdbcType=DATE},
            </if>
            <if test="notWorkDate != null">
                notWorkDate = #{notWorkDate,jdbcType=DATE},
            </if>
            <if test="beginContract != null">
                beginContract = #{beginContract,jdbcType=DATE},
            </if>
            <if test="endContract != null">
                endContract = #{endContract,jdbcType=DATE},
            </if>
            <if test="workAge != null">
                workAge = #{workAge,jdbcType=INTEGER},
            </if>
        </set>
        where id = #{id,jdbcType=INTEGER}
    </update>

3.删除员工信息

controller
删除会返回作用的条数,如果不大于0说明删除失败,数据库无此员工信息

    /**
     * @Author lzp
     * @Description:  删除员工信息
     * @Date: 10:55 2022/7/2
     * @Param:
     * @return:
     */
    @DeleteMapping("/deleteEmpById")
    //@RequestParam作用:可以指定别名 可以设置参数非必须 可以传表单数据,只支持Content-Type: 为 application/x-www-form-urlencoded
    public R deleteEmpById( Integer empId){
        Integer integer = this.employeeEntityService.deleteEmpById(empId);
        if(integer>0)
            return R.ok("删除成功");
        else
            return R.ok("员工不存在");
    }

service

    public Integer deleteEmpById(Integer empId) {
        Integer integer = this.employeeEntityMapper.deleteEmpById(empId);
        return integer;
    }

sql

    <delete id="deleteEmpById">
        delete from employee where id=#{empId}
    </delete>

4.新增用户信息

controller

    /**
     * @Author lzp
     * @Description:  添加员工
     * @Date: 11:11 2022/7/3
     * @Param: []
     * @return: com.lzp.vhrserver.utils.R
     */
    @PostMapping("/addEmp")
    public R addEmp(@RequestBody EmployeeEntity employeeEntity){
        if(this.employeeEntityService.addEmp(employeeEntity)){
            return R.ok("添加成功!");
        }
        return R.error(1,"添加失败");
    }
    
    /**
     * @Author lzp
     * @Description:  新增员工时获取当前员工的Id
     * @Date: 11:02 2022/7/3
     * @Param: []
     * @return: com.lzp.vhrserver.utils.R
     */
    @GetMapping("/getMaxWorkID")
    public R getMaxWorkID(){
        String NewEmpMaxWorkID = this.employeeEntityService.getMaxWorkID();
        return R.ok("").setData(NewEmpMaxWorkID);
    }    

最大id+1,就是要添加的用户id
在这里插入图片描述
service

    public Boolean addEmp(EmployeeEntity employeeEntity) {
        //workState contractTerm notWorkDate workAge id
        employeeEntity.setWorkState("在职");
        employeeEntity.setNotWorkDate(null);//离职日期
        employeeEntity.setWorkAge(null);
        //获取到合同起始时间 和结束时间
        Date beginContract = employeeEntity.getBeginContract();
        Date endContract = employeeEntity.getEndContract();
        //年份相减*12+月份相减 就是合同的总月数
        double month = (Double.parseDouble(yearFormat.format(endContract)) - Double.parseDouble(yearFormat.format(beginContract))) * 12 + (Double.parseDouble(monthFormat.format(endContract)) - Double.parseDouble(monthFormat.format(beginContract)));
        //除以12转为年 用 decimalFormat保留小数位数
        employeeEntity.setContractTerm(Double.parseDouble(decimalFormat.format(month / 12)));
        Integer integer = this.employeeEntityMapper.addEmp(employeeEntity);
        return integer == 1;
    }

在这里插入图片描述
sql

    <insert id="addEmp">
        insert into employee values
        (null,#{emp.name},#{emp.gender},#{emp.birthday},#{emp.idCard},#{emp.wedlock},#{emp.nationId},
         #{emp.nativePlace},#{emp.politicId},#{emp.email},#{emp.phone},#{emp.address},#{emp.departmentId},
         #{emp.jobLevelId},#{emp.posId},#{emp.engageForm},#{emp.tiptopDegree},#{emp.specialty},#{emp.school},
         #{emp.beginDate},#{emp.workState},#{emp.workId},#{emp.contractTerm},#{emp.conversionTime},
         #{emp.notWorkDate},#{emp.beginContract},#{emp.endContract},#{emp.workAge})
    </insert>

5.导出数据

前端点击导出,发送请求到后端,后端将表格返回前端,下载的方式
controller

    /**
     * @Author lzp
     * @Description:  导出员工数据
     * @Date: 16:09 2022/7/3
     * @Param: []
     * @return: com.lzp.vhrserver.utils.R
     */
    @GetMapping ("/exportEmpData")
    public void  exportEmpData(HttpServletResponse response){
        employeeEntityService.exportEmpData(response);
    }

service

    public void exportEmpData(HttpServletResponse response) {
        try {
            //设置下载的信息
            response.setContentType("application/vnd.ms-excel");//格式excel
            response.setCharacterEncoding("utf-8");
            //这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("员工表", "UTF-8");
            //Content-disposition:以下载的方式执行此操作
            response.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xlsx");
            //获取所有的员工信息
            List<EmpExcelVo> employeeEntities = this.getAllEmp();
            //将表格返回给前端
            EasyExcel.write(response.getOutputStream(), EmpExcelVo.class).sheet("员工表").doWrite(employeeEntities);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

查询所有员工sql

    <select id="getAllEmp" resultType="com.lzp.vhrserver.vo.EmpExcelVo" resultMap="empExcelMap">
        select e.*,
            n.name as 'nationName',
            p.name as 'politicName',
            d.name as 'departmentName' ,
            j.name as 'jobLevelName' ,
            po.name as 'posName'
        from employee e
            left join nation n on e.nationId=n.id
            left join politicsstatus p on e.politicId=p.id
            left join department d on e.departmentId=d.id
            left join joblevel j on e.jobLevelId=j.id
            left join position po on e.posId=po.id
    </select>
    <resultMap id="empExcelMap" type="com.lzp.vhrserver.vo.EmpExcelVo">
        <id property="id" column="id" jdbcType="INTEGER"/>
        <result property="name" column="name" jdbcType="VARCHAR"/>
        <result property="gender" column="gender" jdbcType="CHAR"/>
        <result property="birthday" column="birthday" jdbcType="OTHER"/>
        <result property="idCard" column="idCard" jdbcType="CHAR"/>
        <result property="wedlock" column="wedlock" jdbcType="OTHER"/>
        <result property="nationName" column="nationName" jdbcType="VARCHAR"/>
        <result property="nativePlace" column="nativePlace" jdbcType="VARCHAR"/>
        <result property="politicName" column="politicName" jdbcType="VARCHAR"/>
        <result property="email" column="email" jdbcType="VARCHAR"/>
        <result property="phone" column="phone" jdbcType="VARCHAR"/>
        <result property="address" column="address" jdbcType="VARCHAR"/>
        <result property="departmentName" column="departmentName" jdbcType="INTEGER"/>
        <result property="jobLevelName" column="jobLevelName" jdbcType="VARCHAR"/>
        <result property="posName" column="posName" jdbcType="VARCHAR"/>
        <result property="engageForm" column="engageForm" jdbcType="VARCHAR"/>
        <result property="tiptopDegree" column="tiptopDegree" jdbcType="OTHER"/>
        <result property="specialty" column="specialty" jdbcType="VARCHAR"/>
        <result property="school" column="school" jdbcType="VARCHAR"/>
        <result property="beginDate" column="beginDate" jdbcType="DATE"/>
        <result property="workState" column="workState" jdbcType="OTHER"/>
        <result property="workId" column="workID" jdbcType="CHAR"/>
        <result property="contractTerm" column="contractTerm" jdbcType="DOUBLE"/>
        <result property="conversionTime" column="conversionTime" jdbcType="DATE"/>
        <result property="notWorkDate" column="notWorkDate" jdbcType="DATE"/>
        <result property="beginContract" column="beginContract" jdbcType="DATE"/>
        <result property="endContract" column="endContract" jdbcType="DATE"/>
        <result property="workAge" column="workAge" jdbcType="INTEGER"/>
    </resultMap>    

excelvo类
需要对时间特殊处理,easyexcel默认date为java.util.date,如果用sql.date就需要特殊转换器,这里用了util.date+@DateTimeFormat(“yyyy-MM-dd”)注解,可以正确生成excel中的正确时间,导入数据要单独解析时间,不然获得的时间类型不是sql.date,无法保存。必须转换成sql.date。

/**
 * @author:lzp
 * @create: 2022-07-03 15:57
 * @Description: excelVo
 */

@Data
public class EmpExcelVo {
    /**
     * 员工编号
     */
    @ExcelProperty(value = "编号" ,index = 0)
    private Integer id;

    /**
     * 员工姓名
     */
    @ExcelProperty(value = "姓名" ,index = 1)
    private String name;


    /**
     * 工号
     */
    @ExcelProperty(value = "工号" ,index = 2)
    private String workId;

    /**
     * 性别
     */
    @ExcelProperty(value = "性别" ,index = 3)
    private String gender;

    /**
     * 出生日期
     */
    @ExcelProperty(value = "出生日期" ,index =4 )
    @DateTimeFormat("yyyy-MM-dd")
    private java.util.Date birthday;

    /**
     * 身份证号
     */
    @ExcelProperty(value = "身份证号码" ,index = 5)
    private String idCard;

    /**
     * 婚姻状况
     */
    @ExcelProperty(value = "婚姻状况" ,index = 6)
    private String wedlock;

    /**
     * 民族
     */
    @ExcelProperty(value = "民族" ,index = 7)
    private String nationName;

    /**
     * 籍贯
     */
    @ExcelProperty(value = "籍贯" ,index = 8)
    private String nativePlace;

    /**
     * 政治面貌
     */
    @ExcelProperty(value = "政治面貌" ,index = 9)
    private String politicName;

    /**
     * 邮箱
     */
    @ExcelProperty(value = "邮箱" ,index = 10)
    private String email;

    /**
     * 电话号码
     */
    @ExcelProperty(value = "电话号码" ,index = 11)
    private String phone;

    /**
     * 联系地址
     */
    @ExcelProperty(value = "联系地址" ,index = 12)
    private String address;

    /**
     * 所属部门
     */
    @ExcelProperty(value = "所属部门" ,index = 13)
    private String departmentName;

    /**
     * 职称ID
     */
    @ExcelProperty(value = "职称" ,index = 14)
    private String jobLevelName;

    /**
     * 职位ID
     */
    @ExcelProperty(value = "职位" ,index = 15)
    private String posName;

    /**
     * 聘用形式
     */
    @ExcelProperty(value = "聘用形式" ,index = 16)
    private String engageForm;

    /**
     * 最高学历
     */
    @ExcelProperty(value = "最高学历" ,index = 17)
    private String tiptopDegree;

    /**
     * 所属专业
     */
    @ExcelProperty(value = "专业" ,index = 18)
    private String specialty;

    /**
     * 毕业院校
     */
    @ExcelProperty(value = "毕业院校" ,index = 19)
    private String school;

    /**
     * 入职日期
     */
    @ExcelProperty(value = "入职日期" ,index = 20)
    @DateTimeFormat("yyyy-MM-dd")
    private Date beginDate;

    /**
     * 在职状态
     */
    @ExcelProperty(value = "在职状态" ,index = 21)
    private String workState;



    /**
     * 合同期限
     */
    @ExcelProperty(value = "合同期限" ,index = 22)
    private Double contractTerm;

    /**
     * 转正日期
     */
    @ExcelProperty(value = "转正日期" ,index = 23)
    @DateTimeFormat("yyyy-MM-dd")
    private java.util.Date conversionTime;

    /**
     * 离职日期
     */
    @ExcelProperty(value = "离职日期" ,index = 24)
    @DateTimeFormat("yyyy-MM-dd")
    private java.util.Date notWorkDate;

    /**
     * 合同起始日期
     */
    @ExcelProperty(value = "合同起始日期" ,index = 25)
    @DateTimeFormat("yyyy-MM-dd")
    private java.util.Date beginContract;

    /**
     * 合同终止日期
     */
    @ExcelProperty(value = "合同终止日期" ,index = 26)
    @DateTimeFormat("yyyy-MM-dd")
    private java.util.Date endContract;

    /**
     * 工龄
     */
    @ExcelProperty(value = "工龄" ,index = 27)
    private Integer workAge;
}

导出的数据:
在这里插入图片描述

6.导入数据

前端点击导入,将excel文件传给后端,后端将数据保存到数据库。
controller

    @PostMapping("/importEmpData")
    public R importEmpData(MultipartFile file){
        this.employeeEntityService.importEmpData(file);
        return R.ok("导入成功!");
    }

servcie
直接调用read方法,读取文件。主要功能在listener中完成。

    public void importEmpData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(),EmpExcelVo.class,new ExcelListener(this.employeeEntityMapper)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

listener

/**
 *@author: lzp
 *@create: 2022-07-03 21:36:29
 *@description: 导入
 */
public class ExcelListener extends AnalysisEventListener<EmpExcelVo> {
    private EmployeeEntityMapper employeeEntityMapper;

    public ExcelListener(EmployeeEntityMapper employeeEntityMapper) {
        this.employeeEntityMapper = employeeEntityMapper;
    }
	
    @Override
    public void invoke(EmpExcelVo dictEeVo, AnalysisContext analysisContext) {
        //调用方法添加数据库
        //Dict dict = new Dict();
        EmployeeEntity employeeEntity =new EmployeeEntity();
        BeanUtils.copyProperties(dictEeVo,employeeEntity);
        //获取到util.date 出生日期
        Date birthday = dictEeVo.getBirthday();
        //合同起始日期
        Date beginContract = dictEeVo.getBeginContract();
        //合同终止日期
        Date endContract = dictEeVo.getEndContract();
        //入职日期
        Date beginDate = dictEeVo.getBeginDate();
        //离职日期
        Date notWorkDate = dictEeVo.getNotWorkDate();
        //转正日期
        Date conversionTime = dictEeVo.getConversionTime();
        //转化成sql.date employeeEntity中的birthday为sql.date类型的
        employeeEntity.setBirthday(new java.sql.Date(birthday.getTime()));
        employeeEntity.setBeginContract(new java.sql.Date(beginContract.getTime()));
        employeeEntity.setEndContract(new java.sql.Date(endContract.getTime()));
        employeeEntity.setBeginDate(new java.sql.Date(beginDate.getTime()));
        if(null!=notWorkDate)
        employeeEntity.setNotWorkDate(new java.sql.Date(notWorkDate.getTime()));
        employeeEntity.setConversionTime(new java.sql.Date(conversionTime.getTime()));
        //获取id 设置id
        Integer departmentId = employeeEntityMapper.getIdByDepName(dictEeVo.getDepartmentName());
        Integer nationId = employeeEntityMapper.getIdByNaName(dictEeVo.getNationName());
        Integer politicsstatusId = employeeEntityMapper.getIdByPolictName(dictEeVo.getPoliticName());
        Integer jobLevelId = employeeEntityMapper.getIdByJobName(dictEeVo.getJobLevelName());
        Integer positionId = employeeEntityMapper.getIdByPosName(dictEeVo.getPosName());
        employeeEntity.setDepartmentId(departmentId);
        employeeEntity.setNationId(nationId);
        employeeEntity.setPoliticId(politicsstatusId);
        employeeEntity.setJobLevelId(jobLevelId);
        employeeEntity.setPosId(positionId);
        
        employeeEntityMapper.addEmp(employeeEntity);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值