Spring boot整合mybatis實現Restful服務demo

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

Springboot 實現 Restful 服務,基於 HTTP / JSON 傳輸

所以把它歸爲轉載之列。


首先創建數據表並插入一條數據(數據庫名隨意):

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了。。

demo鏈接,哇,又忘記是不能直接添加附件的,很氣




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章