Spring boot(三): 数据库操作,全局异常处理

120 阅读1分钟
  • 创建数据库表
create table if not exists `genshin_camp` (
    `id` int unsigned auto_increment primary key not null comment 'id',
    `name` varchar(32) not null comment '阵营名字',
    `create_time` datetime not null comment '创建时间',
    `update_time` datetime not null comment '更新时间'
)engine=InnoDB default charset=utf8mb4;
  • 模型
@TableName("genshin_camp")
@Data
public class CampEntity {

    private Integer id; // id
    private String name; // 阵营名称
    private LocalDateTime create_time; // 创建时间
    private LocalDateTime update_time; // 更新时间
}
  • Mapper
@Mapper
public interface CampMapper extends BaseMapper<CampEntity> {
}
  • Service
public interface CampService extends IService<CampEntity> {
}
  • Impl
@Service
public class CampServiceImpl extends ServiceImpl<CampMapper, CampEntity> implements CampService {
}
  • 统一返回结果类
@Data
public class GResponse {
    private Integer code; // 0-失败 1-成功
    private String msg; // 信息
    private Object data; // 数据
    
    public static GResponse error(String msg) {
        GResponse r = new GResponse();
        r.code = 0;
        r.msg = msg;
        return r;
    }
    
    public static GResponse success(String msg) {
        GResponse r = new GResponse();
        r.code = 1;
        r.msg = msg;
        return r;
    }
    
    public static GResponse success(String msg,Object data) {
        GResponse r = new GResponse();
        r.code = 1;
        r.msg = msg;
        r.data = data;
        return r;
    }
}
  • 查询操作 在Controller里
@Autowired
private CampService campService;

@GetMapping("/camp")
public GResponse getCamp() {
    List<CampEntity> list = campService.list();
    return GResponse.success("操作成功",list);
}
  • 全局异常处理
@RestControllerAdvice
public class GobalException {

    @ExceptionHandler
    public GResponse handleException(Exception exception) {
        exception.printStackTrace();
        return GResponse.error("服务器异常!!!");
    }

}
  • 全局异常测试
@GetMapping("/exception")
public GResponse testException() {
    Integer r = 10 / 0;
    return GResponse.success("操作成功");
}