springboot是spring家族中的一个全新框架,用来简化spring程序的创建和开发过程。以前我们写项目的时候需要配置大量的文件然后进行整合,而springboot抛弃了繁琐的xml配置过程,采用大量默认的配置来简化我们的spring开发过程。
Springboot+Mybatis的整合:
Controller类 (只负责接收和发送数据)
Service类(处理逻辑)
Mapper类(数据库操作)
大概流程:
启动类运行时会将参数传递给Controller类,在Controller类的相应方法中调用Service类进行逻辑处理,继续在Service类中调用Mapper类根据需求对数据库进行操作,操作完成后返回到将需要传递的参数返回Service类中,Service类再将参数返回到Controller类
启动类:
@ServletComponentScan//开启了对servlet组件的支持
@SpringBootApplication
public class SpringbootMybatisCase1Application {public static void main(String[] args) {SpringApplication.run(SpringbootMybatisCase1Application.class, args);}}
Controller类:
@Slf4j//记录日志
@RestController
public class LoginController {@Autowiredprivate EmpService empService;@PostMapping("/login")public Result login(@RequestBody Emp emp){log.info("员工登录:",emp);Emp e=empService.login(emp);//登陆成功,生成令牌,下发令牌if(e!=null){Map<String, Object> claims=new HashMap<>();claims.put("id",e.getId());claims.put("name",e.getName());claims.put("username",e.getUsername());String jwt =JwtUtils.generateJwt(claims);return Result.success(jwt);}//登录失败,返回错误信息return Result.error("用户名或密码错误");}
}
Service类:
public interface DeptService {List<Dept> list();void delete(Integer id);void add(Dept dept);Dept find(Integer id);void update(Dept dept);
}
@Service
public class DeptServiceImpl implements DeptService {@Autowiredprivate DeptMapper deptMapper;@Autowiredprivate EmpMapper empMapper;@Autowiredprivate DeptLogService deptLogService;@MyLog@Overridepublic List<Dept> list(){return deptMapper.list();}@MyLog@Transactional(rollbackFor = Exception.class)//出现所有异常都会进行事务回滚@Overridepublic void delete(Integer id){try {deptMapper.delete(id);//int i=1/0;empMapper.deleteByDeptId(id);} finally {DeptLog deptLog=new DeptLog();deptLog.setCreateTime(LocalDateTime.now());deptLog.setDescription("执行了解散部门的操作,此次解散的是"+id+"号部门");deptLogService.insert(deptLog);}}@Overridepublic void add(Dept dept){dept.setCreateTime(LocalDateTime.now());dept.setUpdateTime(LocalDateTime.now());deptMapper.add(dept);}@Overridepublic Dept find(Integer id){Dept dept=deptMapper.find(id);return dept;}@Overridepublic void update(Dept dept){dept.setUpdateTime(LocalDateTime.now());deptMapper.update(dept);}
}
Mapper类:
@Mapper
public interface DeptMapper {//查询全部部门数据@Select("select * from dept")List<Dept> list();@Delete("delete from dept where id=#{id}")void delete(Integer id);@Insert("insert into dept(name,create_time,update_time) values (#{name},#{createTime},#{updateTime})")void add(Dept dept);@Select("select * from dept where id=#{id}")Dept find(Integer id);@Update("update dept set name=#{name},update_time=#{updateTime} where id=#{id}")void update(Dept dept);
}