1. 程式人生 > >Spring boot整合mybatis實現Restful服務demo

Spring boot整合mybatis實現Restful服務demo

首先要宣告,這個demo很大程度上參考了這篇文章:

所以把它歸為轉載之列。

首先建立資料表並插入一條資料(資料庫名隨意):

DROP TABLE IF EXISTS  `city`;
CREATE TABLE `city` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '城市編號',
  `province_id` int(10) unsigned  NOT NULL COMMENT '省份編號',
  `city_name` varchar(25) DEFAULT NULL COMMENT '城市名稱',
  `description` varchar(25) DEFAULT NULL COMMENT '描述',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
INSERT city VALUES (1 ,1,'溫嶺市','BYSocket 的家在溫嶺。');

接下去是專案結構:


新增依賴:

 <!-- Spring Boot 啟動父依賴 -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.1.RELEASE</version>
    </parent>

    <properties>
        <mybatis-spring-boot>1.2.0</mybatis-spring-boot>
        <mysql-connector>5.1.39</mysql-connector>
    </properties>

    <dependencies>

        <!-- Spring Boot Web 依賴 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- Spring Boot Test 依賴 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- Spring Boot Mybatis 依賴 -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>${mybatis-spring-boot}</version>
        </dependency>

        <!-- MySQL 連線驅動依賴 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql-connector}</version>
        </dependency>

        <!-- Junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>

然後說說三個比較重要的檔案,並附加部分說明:

1、配置檔案application.properties(名字不可變)

## 資料來源配置
spring.datasource.url=jdbc:mysql://localhost:3306/springbootdb?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

## Mybatis 配置
mybatis.typeAliasesPackage=haha.domain
mybatis.mapperLocations=classpath*:haha/mapper/*.xml

各配置項根據自己情況修改,應該是一目瞭然的。

附:如果mapper像我一樣不放在resources目錄下的話,請在pom.xml中新增如下程式碼,否則你的.xml檔案可能不在build檔案中。

    <!--將xml檔案打包-->
    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>

2、啟動檔案Application.java

// Spring Boot 應用的標識
@SpringBootApplication
// mapper 介面類掃描包配置
@MapperScan("haha.dao")
public class Application {

    public static void main(String[] args) {
        // 程式啟動入口
        // 啟動嵌入式的 Tomcat 並初始化 Spring 環境及其各 Spring 元件
        SpringApplication.run(Application.class,args);
    }
}
主要作用是建立一個Spring應用上下文(Application Context)。另外,注意這裡的mapper介面類掃描包的配置,還有就是如果是部署到tomcat下這裡也會進行修改。(自行百度吧,我就懶得說啦~~)

3、Controller類
@RestController
//是一類特殊的@Controller,它的返回值直接作為HTTP Response的Body部分返回給瀏覽器。
//@Controller並非直接將字串返回給瀏覽器,而是尋找名字為返回值的模板進行渲染
public class CityController {

    @Autowired
    private CityService cityService;

    //@RequestMapping註解表明該方法處理那些URL對應的HTTP請求,也就是我們常說的URL路由(routing),請求的分發工作是有Spring完成的。
    //URL中的變數——PathVariable
    //例如@RequestMapping("/api/city/{id}")
    //URL中的變數可以用{variableName}來表示,同時在方法的引數中加上@PathVariable("variableName"),那麼當請求被轉發給該方法處理時,對應的URL中的變數會被自動賦值給被@PathVariable註解的引數
    @RequestMapping(value = "/api/city/{id}", method = RequestMethod.GET)
    public City findOneCity(@PathVariable("id") Long id) {
        return cityService.findCityById(id);
    }
}
根據註釋應當是一目瞭然的,在此我便不多贅述了。


最後便是運行了,啟動main函式,發現其實這段程式是個web應用,放置在內嵌的Servlet容器中。


訪問url:http://127.0.0.1:8080/api/city/1


以上便是全部內容啦,謝謝閱讀~~

差點忘了放上demo了。。