day01 新增员工业务逻辑整理
EmployeeController.java
@PostMapping
@ApiOperation("新增员工")
public Result save(@RequestBody EmployeeDTO employeeDTO){
System.out.println("当前线程的ID:" + Thread.currentThread().getId());
log.info("新增员工:{}", employeeDTO);
employeeService.save(employeeDTO);
return Result.success();
}
调用service接口中的方法
public interface EmployeeService {
void save(EmployeeDTO employeeDTO);
}
service实现类中重写方法
@Service
public class EmployeeServiceImpl implements EmployeeService {
@Autowired
private EmployeeMapper employeeMapper;
public void save(EmployeeDTO employeeDTO) {
System.out.println("当前线程的ID:" + Thread.currentThread().getId());
Employee employee = new Employee();
//对象属性拷贝
BeanUtils.copyProperties(employeeDTO, employee);
//设置未拷贝的属性
//设置账号状态(1:启用,0:停用)
employee.setStatus(StatusConstant.ENABLE);
//设置密码默认:123456
employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));
employee.setCreateTime(LocalDateTime.now());
employee.setUpdateTime(LocalDateTime.now());
//todo 后期需要改为当前登录用户的id
employee.setCreateUser(BaseContext.getCurrentId());
employee.setUpdateUser(BaseContext.getCurrentId());
# 调用mapper中的insert方法
employeeMapper.insert(employee);
}
}
mapper中的方法
//简单SQL语句直接使用注解
@Mapper
public interface EmployeeMapper {
/**
* 插入员工数据
* @param employee
*/
@Insert("insert into employee(name, username, password, phone, sex, id_number, status, create_time, update_time, create_user, " + "update_user) values (#{name}, #{username}, #{password}, #{phone}, #{sex}, #{idNumber}, #{status}, #{createTime}, #{updateTime}, "+ "#{createUser}, #{updateUser})")
void insert(Employee employee);
}
两个问题
问题一
GlobalExceptionHandler.java
捕获异常信息向前端传送数据
/**
* 全局异常处理器,处理项目中抛出的业务异常
*/
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
/**
* 处理SQL异常
* @param ex
* @return
*/
@ExceptionHandler
public Result exceptionHandler(SQLIntegrityConstraintViolationException ex){
//Duplicate entry 'zhangsan' for key 'employee.idx_username'
String message = ex.getMessage();
if(message.contains("Duplicate entry")){
String[] split = message.split(" ");
String username = split[2];
String msg = username + "已存在";
return Result.error(msg);
}else {
return Result.error(MessageConstant.UNKNOWN_ERROR);
}
}
}
问题二
通过Thread设置当前线程的ID
JWT
校验令牌的时候使用Thread存储值
//2、校验令牌
try {
log.info("jwt校验:{}", token);
Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), token);
Long empId = Long.valueOf(claims.get(JwtClaimsConstant.EMP_ID).toString());
log.info("当前员工id:", empId);
BaseContext.setCurrentId(empId);
//3、通过,放行
return true;
} catch (Exception ex) {
//4、不通过,响应401状态码
response.setStatus(401);
return false;
}
Service实现类中调用
用户登录的时候取出ID
employee.setCreateUser(BaseContext.getCurrentId());
employee.setUpdateUser(BaseContext.getCurrentId());
Base是封装好的类
public class BaseContext {
public static ThreadLocal<Long> threadLocal = new ThreadLocal<>();
public static void setCurrentId(Long id) {
threadLocal.set(id);
}
public static Long getCurrentId() {
return threadLocal.get();
}
public static void removeCurrentId() {
threadLocal.remove();
}
}