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 依赖


<dependency>
    <groupId>org.mybatis.spring.bootgroupId>
    <artifactId>mybatis-spring-boot-starterartifactId>
    <version>1.2.0version>
dependency>


<dependency>
    <groupId>mysqlgroupId>
    <artifactId>mysql-connector-javaartifactId>
    <version>5.1.39version>
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);
    }
}

项目的整体结构

Spring Boot 基础篇之 整合Mybatis 实现 RESTful API_第1张图片

controller 实现RESTful API

@RestController
public class HeroController {
    @Autowired
    private HeroService heroService;
    //查询所有的hero
    @RequestMapping(value="/hero",method=RequestMethod.GET)
    public List getHeroList(){
        List 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

Spring Boot 基础篇之 整合Mybatis 实现 RESTful API_第2张图片

访问 http://localhost:8080/hero

Spring Boot 基础篇之 整合Mybatis 实现 RESTful API_第3张图片

项目下载

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

你可能感兴趣的:(SpringBoot)