Spring Boot 基础篇之 整合Mybatis 实现 RESTful API

采用Sprng Boot集成Mybatis 没有使用 Mybatis Annotation 这种,是使用 xml 配置 SQL。因为我觉得 SQL 和业务代码应该隔离,方便和 DBA 校对 SQL。二者 XML 对较长的 SQL 比较清晰。

数据库准备
CREATE TABLE `hero` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '英雄id',
  `name` varchar(50) NOT NULL COMMENT '英雄名称',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8
INSERT hero VALUES (1 ,'大乔')
INSERT hero VALUES (2 ,'刘备')
pom.xml 中添加 mybatis 依赖
<!-- Spring Boot Mybatis 依赖 -->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.2.0</version>
</dependency>

<!-- MySQL 连接驱动依赖 -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.39</version>
</dependency>
在 application.properties 应用配置文件,增加 Mybatis 相关配置
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

## Mybatis 
mybatis.typeAliasesPackage=com.lol.entity
mybatis.mapperLocations=classpath\:mapper/*.xml

mybatis 其他配置相关详情如下:

  • mybatis.config = mybatis 配置文件名称
  • mybatis.mapperLocations = mapper xml 文件地址
  • mybatis.typeAliasesPackage = 实体类包路径
  • mybatis.typeHandlersPackage = type handlers 处理器包路径
  • mybatis.check-config-location = 检查 mybatis 配置是否存在,一般命名为 mybatis-config.xml
  • mybatis.executorType = 执行模式。默认是 SIMPLE
应用启动类添加注解 MapperScan
@SpringBootApplication
//mapper 接口类扫描包配置
@MapperScan("com.lol.dao")
public class LolApplication {
    public static void main(String[] args) {
        SpringApplication.run(LolApplication.class, args);
    }
}
项目的整体结构

image

controller 实现RESTful API
@RestController
public class HeroController {
    @Autowired
    private HeroService heroService;
    //查询所有的hero
    @RequestMapping(value="/hero",method=RequestMethod.GET)
    public List<Hero> getHeroList(){
        List<Hero> heroList = heroService.getHeroList();
        return heroList;
    }
    //根据id查询hero
    @RequestMapping(value="/hero/{id}",method=RequestMethod.GET)
    public Hero getHero(@PathVariable("id") Integer id){
        Hero hero = heroService.getHeroById(id);
        return hero;
    }

}
运行项目

访问 http://localhost:8080/hero/1

image

访问 http://localhost:8080/hero

image

项目下载

github路径:https://github.com/YaoZhiQi/SpringBoot-Mybatis.git

  • 6
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

CiBa-YAO

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值