案例-部门管理-新增
package com.itheima.controller;
import com.itheima.pojo.Dept;
import com.itheima.pojo.Result;
import com.itheima.service.DeptService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@Slf4j//lombok提供的注解(为了简化日志定义对象的操作)
@RestController
public class DeptController {
@Autowired
private DeptService deptService;
//定义日志记录对象
//private static Logger log = LoggerFactory.getLogger(DeptController.class);
//@RequestMapping(value = "/depts",method = RequestMethod.GET)//指定请求方式为GET
/*查询部门数据*/
@GetMapping("/depts")
public Result list() {
log.info("查询全部部门数据");
//调用service查询部门数据
List<Dept> deptList = deptService.list();
return Result.success(deptList);
}
/*删除部门*/
@DeleteMapping("/depts/{id}")
public Result deleteDept(@PathVariable Integer id) {
log.info("删除部门"+id);
deptService.delete(id);
return Result.success();
}
/*添加部门*/
@PostMapping("/depts")
public Result add(@RequestBody Dept dept){
log.info("添加部门"+dept);
deptService.add(dept);
return Result.success();
}
}
package com.itheima.service;
import com.itheima.pojo.Dept;
import java.util.List;
public interface DeptService {
//查询全部部门数据
List<Dept> list();
//根据ID删除部门
void delete(Integer id);
/*新增部门*/
void add(Dept dept);
}
package com.itheima.service.impl;
import com.itheima.mapper.DeptMapper;
import com.itheima.pojo.Dept;
import com.itheima.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.List;
@Service
public class DeptServiceImpl implements DeptService {
@Autowired
private DeptMapper deptMapper;
/*查询全部部门*/
@Override
public List<Dept> list() {
return deptMapper.list();
}
/*根据ID删除部门*/
@Override
public void delete(Integer id) {
deptMapper.delete(id);
}
/*新增员工*/
@Override
public void add(Dept dept) {
dept.setCreateTime(LocalDateTime.now());
dept.setUpdateTime(LocalDateTime.now());
deptMapper.add(dept);
}
}
package com.itheima.mapper;
import com.itheima.pojo.Dept;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;
@Mapper
public interface DeptMapper {
//查询全部部门数据
@Select("select * from dept")
List<Dept> list();
/*根据ID删除部门*/
@Delete("delete from dept where id=#{id}")
void delete(Integer id);
/*新增部门*/
@Insert("insert into dept (name, create_time, update_time) value (#{name},#{createTime},#{updateTime})")
void add(Dept dept);
}