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

来源:互联网 发布:吉林快3遗漏 数据 编辑:程序博客网 时间:2024/05/17 15:39

采用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/testspring.datasource.username=rootspring.datasource.password=rootspring.datasource.driver-class-name=com.mysql.jdbc.Driver## Mybatis mybatis.typeAliasesPackage=com.lol.entitymybatis.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

@RestControllerpublic 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

5 0