基於SpringBoot開發一個Restful服務,實現增刪改查功能

  • 2019 年 10 月 6 日
  • 筆記

前言

在去年的時候,在各種渠道中略微的了解了SpringBoot,在開發web項目的時候是如何的方便、快捷。但是當時並沒有認真的去學習下,畢竟感覺自己在Struts和SpringMVC都用得不太熟練。不過在看了很多關於SpringBoot的介紹之後,並沒有想像中的那麼難,於是開始準備學習SpringBoot。

在閑暇之餘的時候,看了下SpringBoot實戰以及一些大神關於SpringBoot的部落格之後,開始寫起了我的第一個SpringBoot的項目。在能夠對SpringBoot進行一些簡單的開發Restful風格介面實現CRUD功能之後,於是便有了本篇博文。

SpringBoot介紹

Spring Boot是由Pivotal團隊提供的全新框架,其設計目的是用來簡化新Spring應用的初始搭建以及開發過程。該框架使用了特定的方式來進行配置,從而使開發人員不再需要定義樣板化的配置。 簡單的來說就是,只需幾個jar和一些簡單的配置,就可以快速開發項目。 假如我就想簡單的開發一個對外的介面,那麼只需要以下程式碼就可以了。

一個主程式啟動springBoot

@SpringBootApplication  public class Application {      public static void main(String[] args) {          SpringApplication.run(Application.class, args);      }  }  

控制層

@RestController  public class HelloWorldController {      @RequestMapping("/hello")      public String index() {          return "Hello World";      }   }  

成功啟動主程式之後,編寫控制層,然後在瀏覽器輸入 http://localhost:8080//hello 便可以查看資訊。

感覺使用SpringBoot開發程式是不是非常的簡單呢!

用SpringBoot實戰的話來說:

這裡沒有配置,沒有web.xml,沒有構建說明,甚至沒有應用伺服器,但這就是整個應用程式了。SpringBoot會搞定執行應用程式所需的各種後勤工作,你只要搞定應用程式的程式碼就好。

基於SpringBoot開發一個Restful服務

一、開發準備

1.1 資料庫和表

首先,我們需要在MySql中創建一個資料庫和一張表

資料庫的名稱為 springboot,表名稱為 t_user

腳本如下:

CREATE DATABASE `springboot`;    USE `springboot`;    DROP TABLE IF EXISTS `t_user`;    CREATE TABLE `t_user` (    `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'id',    `name` varchar(10) DEFAULT NULL COMMENT '姓名',    `age` int(2) DEFAULT NULL COMMENT '年齡',    PRIMARY KEY (`id`)  ) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8;  

1.2 maven相關依賴

因為我們使用Maven創建的,所以需要添加SpringBoot的相關架包。

這裡Maven的配置如下:

springBoot最核心的jar spring-boot-starter :核心模組,包括自動配置支援、日誌和YAML;

<parent>          <groupId>org.springframework.boot</groupId>          <artifactId>spring-boot-starter-parent</artifactId>          <version>1.5.9.RELEASE</version>          <relativePath/>      </parent>         <properties>          <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>          <java.version>1.7</java.version>            <mybatis-spring-boot>1.2.0</mybatis-spring-boot>          <mysql-connector>5.1.39</mysql-connector>        </properties>          <dependencies>          <dependency>              <groupId>org.springframework.boot</groupId>              <artifactId>spring-boot-starter-web</artifactId>          </dependency>          <dependency>              <groupId>org.springframework.boot</groupId>              <artifactId>spring-boot-starter-thymeleaf</artifactId>          </dependency>          <dependency>              <groupId>org.springframework.boot</groupId>              <artifactId>spring-boot-starter-data-jpa</artifactId>          </dependency>              <dependency>              <groupId>org.springframework.boot</groupId>              <artifactId>spring-boot-devtools</artifactId>              <optional>true</optional>          </dependency>            <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>        </dependencies>        <build>          <plugins>          <!--運用SpringBoot 插件  使用spring-boot-devtools模組的應用,當classpath中的文件有改變時,會自動重啟! -->              <plugin>                  <groupId>org.springframework.boot</groupId>                  <artifactId>spring-boot-maven-plugin</artifactId>                  <configuration>                      <fork>true</fork>                  </configuration>              </plugin>          </plugins>      </build>  

二、工程說明

成功創建好資料庫以及下載好相應架包之後。

我們來正式開發SpringBoot項目。

2.1工程結構圖:

首先確定工程結構,這裡我就簡單的說明下了。

com.pancm.web – Controller 層 com.pancm.dao – 數據操作層 DAO com.pancm.bean – 實體類 com.pancm.service – 業務邏輯層 Application – 應用啟動類 application.properties – 應用配置文件,應用啟動會自動讀取配置

2.2 自定義配置文件

一般我們需要一些自定義的配置,例如配置jdbc的連接配置,在這裡我們可以用 application.properties 進行配置。數據源實際的配置以各位的為準。

## 數據源配置  spring.datasource.url=jdbc:mysql://localhost:3306/springBoot?useUnicode=true&characterEncoding=utf8  spring.datasource.username=root  spring.datasource.password=123456  spring.datasource.driver-class-name=com.mysql.jdbc.Driver      ## Mybatis 配置  # 配置為 com.pancm.bean 指向實體類包路徑。  mybatis.typeAliasesPackage=com.pancm.bean  # 配置為 classpath 路徑下 mapper 包下,* 代表會掃描所有 xml 文件。  mybatis.mapperLocations=classpath:mapper/*.xml  

三、程式碼編寫

在創建好相關工程目錄之後,我們開始來編寫相應的程式碼。

3.1 實體類編寫

由於我們這裡只是用於測試,只在資料庫中創建了一張t_user表,所以這裡我們就只創建一個User實體類,裡面的欄位對應t_user表的欄位。

示例程式碼如下:

 public class User {       /** 編號 */       private int id;       /** 姓名 */       private String name;       /** 年齡 */       private int age;         public User(){       }     public class User {       /** 編號 */       private int id;       /** 姓名 */       private String name;       /** 年齡 */       private int age;         public User(){       }  //   getter和 setter 略  }  

3.2 Dao層編寫

在以前的Dao層這塊,hibernate和mybatis 都可以使用註解或者使用mapper配置文件。在這裡我們使用spring的JPA來完成基本的增刪改查。

說明:

一般有兩種方式實現與資料庫實現CRUD:

  • 第一種是xml的mapper配置。
  • 第二種是使用註解,@Insert、@Select、@Update、@Delete 這些來完成。本篇使用的是第二種。
import org.apache.ibatis.annotations.Delete;  import org.apache.ibatis.annotations.Insert;  import org.apache.ibatis.annotations.Mapper;  import org.apache.ibatis.annotations.Result;  import org.apache.ibatis.annotations.Results;  import org.apache.ibatis.annotations.Select;  import org.apache.ibatis.annotations.Update;  import org.springframework.data.repository.query.Param;  import com.pancm.bean.User;    @Mapper  public interface UserDao {        /**       * 用戶數據新增       */       @Insert("insert into t_user(id,name,age) values (#{id},#{name},#{age})")        void addUser(User user);         /**        * 用戶數據修改        */       @Update("update t_user set name=#{name},age=#{age} where id=#{id}")        void updateUser(User user);         /**        * 用戶數據刪除       */       @Delete("delete from t_user where id=#{id}")       void deleteUser(int id);          /**       * 根據用戶名稱查詢用戶資訊       *       */      @Select("SELECT id,name,age FROM t_user where name=#{userName}")      User findByName(@Param("userName") String userName);       /**       * 查詢所有       */      @Select("SELECT id,name,age FROM t_user")      List<User> findAll();      }  

說明:

  • mapper : 在介面上添加了這個註解表示這個介面是基於註解實現的CRUD。
  • Results: 返回的map結果集,property 表示User類的欄位,column 表示對應資料庫的欄位。
  • Param:sql條件的欄位。
  • Insert、Select、Update、Delete:對應資料庫的增、查、改、刪。

3.3 Service 業務邏輯層

這塊和hibernate、mybatis的基本一樣。

程式碼如下:

介面

import com.pancm.bean.User;    /**   *  * Title: UserService  * Description:用戶介面  * Version:1.0.0  * @author pancm   */  public interface UserService {        /**       * 新增用戶       * @param user       * @return       */      boolean addUser(User user);        /**       * 修改用戶       * @param user       * @return       */      boolean updateUser(User user);          /**       * 刪除用戶       * @param id       * @return       */      boolean deleteUser(int id);         /**       * 根據用戶名字查詢用戶資訊       * @param userName       */      User findUserByName(String userName);            /**       * 查詢所有       * @return       */      List<User> findAll();  }  

實現類

import org.springframework.beans.factory.annotation.Autowired;  import org.springframework.stereotype.Service;    import com.pancm.bean.User;  import com.pancm.dao.UserDao;  import com.pancm.service.UserService;    /**   *  * Title: UserServiceImpl  * Description:  * 用戶操作實現類  * Version:1.0.0  * @author pancm   */  @Service  public class UserServiceImpl implements UserService {      @Autowired      private UserDao userDao;          @Override      public boolean addUser(User user) {          boolean flag=false;          try{              userDao.addUser(user);              flag=true;          }catch(Exception e){              e.printStackTrace();          }          return flag;      }        @Override      public boolean updateUser(User user) {          boolean flag=false;          try{              userDao.updateUser(user);              flag=true;          }catch(Exception e){              e.printStackTrace();          }          return flag;      }        @Override      public boolean deleteUser(int id) {          boolean flag=false;          try{              userDao.deleteUser(id);              flag=true;          }catch(Exception e){              e.printStackTrace();          }          return flag;      }        @Override      public User findUserByName(String userName) {          return userDao.findByName(userName);      }          @Override      public List<User> findAll() {          return userDao.findAll();      }  }  

3.4 Controller 控制層

控制層這塊和springMVC很像,但是相比而言要簡潔不少。

說明:

  • RestController:默認類中的方法都會以json的格式返回。
  • RequestMapping: 介面路徑配置。
  • method : 請求格式。
  • RequestParam: 請求參數。

具體實現如下:

import org.springframework.beans.factory.annotation.Autowired;  import org.springframework.web.bind.annotation.RequestMapping;  import org.springframework.web.bind.annotation.RequestMethod;  import org.springframework.web.bind.annotation.RequestParam;  import org.springframework.web.bind.annotation.RestController;    import com.pancm.bean.User;  import com.pancm.service.UserService;      /**   *  * Title: UserRestController  * Description:  * 用戶數據操作介面  * Version:1.0.0  * @author pancm   */  @RestController  @RequestMapping(value = "/api/user")  public class UserRestController {      @Autowired      private UserService userService;        @RequestMapping(value = "/user", method = RequestMethod.POST)      public boolean addUser( User user) {          System.out.println("開始新增...");          return userService.addUser(user);      }        @RequestMapping(value = "/user", method = RequestMethod.PUT)      public boolean updateUser( User user) {          System.out.println("開始更新...");          return userService.updateUser(user);      }        @RequestMapping(value = "/user", method = RequestMethod.DELETE)      public boolean delete(@RequestParam(value = "userName", required = true) int userId) {          System.out.println("開始刪除...");          return userService.deleteUser(userId);      }          @RequestMapping(value = "/user", method = RequestMethod.GET)      public User findByUserName(@RequestParam(value = "userName", required = true) String userName) {          System.out.println("開始查詢...");          return userService.findUserByName(userName);      }          @RequestMapping(value = "/userAll", method = RequestMethod.GET)      public List<User> findByUserAge() {          System.out.println("開始查詢所有數據...");          return userService.findAll();      }  }  

3.5 Application 主程式

SpringApplication 則是用於從main方法啟動Spring應用的類。 默認,它會執行以下步驟:

  1. 創建一個合適的ApplicationContext實例 (取決於classpath)。
  2. 註冊一個CommandLinePropertySource,以便將命令行參數作為Spring properties。
  3. 刷新application context,載入所有單例beans。
  4. 激活所有CommandLineRunner beans。

直接使用main啟動該類,SpringBoot便自動化配置了。

ps:即使是現在我依舊覺得這個實在是太厲害了。

該類的一些註解說明:

SpringBootApplication:開啟組件掃描和自動配置。 MapperScan: mapper 介面類掃描包配置

程式碼如下:

import org.mybatis.spring.annotation.MapperScan;  import org.springframework.boot.SpringApplication;  import org.springframework.boot.autoconfigure.SpringBootApplication;  /**   *  * Title: Application  * Description:  * springBoot 主程式  * Version:1.0.0  * @author pancm  * @date 2018年1月5日   */    @SpringBootApplication  @MapperScan("com.pancm.dao")  public class Application {      public static void main(String[] args) {          // 啟動嵌入式的 Tomcat 並初始化 Spring 環境及其各 Spring 組件          SpringApplication.run(Application.class, args);          System.out.println("程式正在運行...");      }  }  

四、程式碼測試

程式碼編寫完之後,我們進行程式碼的測試。

啟動Application 之後,使用postman工具進行介面的測試。

postman的使用教程可以看這篇部落格:

http://www.panchengming.com/2017/04/24/pancm12/

測試結果如下:

這裡只使用了一個get和post測試,實際方法都測試過了,但是感覺沒必要貼圖了。

項目放到github上面去了:

https://github.com/xuwujing/springBoot