日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 前端技术 > javascript >内容正文

javascript

基于 Spring Boot 的 Restful 风格实现增删改查

發(fā)布時(shí)間:2025/3/21 javascript 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 基于 Spring Boot 的 Restful 风格实现增删改查 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

前言

在去年的時(shí)候,在各種渠道中略微的了解了SpringBoot,在開發(fā)web項(xiàng)目的時(shí)候是如何的方便、快捷。但是當(dāng)時(shí)并沒有認(rèn)真的去學(xué)習(xí)下,畢竟感覺自己在Struts和SpringMVC都用得不太熟練。不過在看了很多關(guān)于SpringBoot的介紹之后,并沒有想象中的那么難,于是開始準(zhǔn)備學(xué)習(xí)SpringBoot。在閑暇之余的時(shí)候,看了下SpringBoot實(shí)戰(zhàn)以及一些大神關(guān)于SpringBoot的博客之后,開始寫起了我的第一個(gè)SpringBoot的項(xiàng)目。在能夠?qū)pringBoot進(jìn)行一些簡(jiǎn)單的開發(fā)Restful風(fēng)格接口實(shí)現(xiàn)CRUD功能之后,于是便有了本篇博文。

SpringBoot介紹

Spring Boot是由Pivotal團(tuán)隊(duì)提供的全新框架,其設(shè)計(jì)目的是用來簡(jiǎn)化新Spring應(yīng)用的初始搭建以及開發(fā)過程。該框架使用了特定的方式來進(jìn)行配置,從而使開發(fā)人員不再需要定義樣板化的配置。簡(jiǎn)單的來說就是,只需幾個(gè)jar和一些簡(jiǎn)單的配置,就可以快速開發(fā)項(xiàng)目。假如我就想簡(jiǎn)單的開發(fā)一個(gè)對(duì)外的接口,那么只需要以下代碼就可以了。

一個(gè)主程序啟動(dòng)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";}}

成功啟動(dòng)主程序之后,編寫控制層,然后在瀏覽器輸入 http://localhost:8080//hello 便可以查看信息。

感覺使用SpringBoot開發(fā)程序是不是非常的簡(jiǎn)單呢!用SpringBoot實(shí)戰(zhàn)的話來說:

這里沒有配置,沒有web.xml,沒有構(gòu)建說明,甚至沒有應(yīng)用服務(wù)器,但這就是整個(gè)應(yīng)用程序了。SpringBoot會(huì)搞定執(zhí)行應(yīng)用程序所需的各種后勤工作,你只要搞定應(yīng)用程序的代碼就好。

基于SpringBoot開發(fā)一個(gè)Restful服務(wù)

一、開發(fā)準(zhǔn)備

1.1 數(shù)據(jù)庫(kù)和表

首先,我們需要在MySql中創(chuàng)建一個(gè)數(shù)據(jù)庫(kù)和一張表 數(shù)據(jù)庫(kù)的名稱為?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相關(guān)依賴

因?yàn)槲覀兪褂肕aven創(chuàng)建的,所以需要添加SpringBoot的相關(guān)架包。這里Maven的配置如下: springBoot最核心的jar spring-boot-starter :核心模塊,包括自動(dòng)配置支持、日志和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?連接驅(qū)動(dòng)依賴?--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>${mysql-connector}</version></dependency></dependencies><build><plugins><!--運(yùn)用SpringBoot 插件??使用spring-boot-devtools模塊的應(yīng)用,當(dāng)classpath中的文件有改變時(shí),會(huì)自動(dòng)重啟!?--><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><configuration><fork>true</fork></configuration></plugin></plugins></build>

二、工程說明

成功創(chuàng)建好數(shù)據(jù)庫(kù)以及下載好相應(yīng)架包之后。我們來正式開發(fā)SpringBoot項(xiàng)目。

2.1工程結(jié)構(gòu)圖:

首先確定工程結(jié)構(gòu),這里我就簡(jiǎn)單的說明下了。

com.pancm.web - Controller 層 com.pancm.dao - 數(shù)據(jù)操作層 DAO com.pancm.bean - 實(shí)體類 com.pancm.service - 業(yè)務(wù)邏輯層 Application - 應(yīng)用啟動(dòng)類 application.properties - 應(yīng)用配置文件,應(yīng)用啟動(dòng)會(huì)自動(dòng)讀取配置

2.2 自定義配置文件

一般我們需要一些自定義的配置,例如配置jdbc的連接配置,在這里我們可以用?application.properties?進(jìn)行配置。數(shù)據(jù)源實(shí)際的配置以各位的為準(zhǔn)。

# 數(shù)據(jù)源配置 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 指向?qū)嶓w類包路徑。 mybatis.typeAliasesPackage=com.pancm.bean # 配置為 classpath 路徑下 mapper 包下,* 代表會(huì)掃描所有 xml 文件。 mybatis.mapperLocations=classpath\:mapper/*.xml

三、代碼編寫

在創(chuàng)建好相關(guān)工程目錄之后,我們開始來編寫相應(yīng)的代碼。

3.1 實(shí)體類編寫

由于我們這里只是用于測(cè)試,只在數(shù)據(jù)庫(kù)中創(chuàng)建了一張t_user表,所以這里我們就只創(chuàng)建一個(gè)User實(shí)體類,里面的字段對(duì)應(yīng)t_user表的字段。

示例代碼如下:

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

3.2 Dao層編寫

在以前的Dao層這塊,hibernate和mybatis 都可以使用注解或者使用mapper配置文件。在這里我們使用spring的JPA來完成基本的增刪改查。說明: 一般有兩種方式實(shí)現(xiàn)與數(shù)據(jù)庫(kù)實(shí)現(xiàn)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?{/***?用戶數(shù)據(jù)新增*/@Insert("insert?into?t_user(id,name,age)?values?(#{id},#{name},#{age})")void?addUser(User?user);/***?用戶數(shù)據(jù)修改*/@Update("update?t_user?set?name=#{name},age=#{age}?where?id=#{id}")void?updateUser(User?user);/***?用戶數(shù)據(jù)刪除*/@Delete("delete?from?t_user?where?id=#{id}")void?deleteUser(int?id);/***?根據(jù)用戶名稱查詢用戶信息**/@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 : 在接口上添加了這個(gè)注解表示這個(gè)接口是基于注解實(shí)現(xiàn)的CRUD。

  • Results: 返回的map結(jié)果集,property 表示User類的字段,column 表示對(duì)應(yīng)數(shù)據(jù)庫(kù)的字段。

  • Param:sql條件的字段。

  • Insert、Select、Update、Delete:對(duì)應(yīng)數(shù)據(jù)庫(kù)的增、查、改、刪。

3.3 Service 業(yè)務(wù)邏輯層

這塊和hibernate、mybatis的基本一樣。代碼如下:

接口

import?com.pancm.bean.User;/*** *?Title:?UserService *?Description:用戶接口 *?Version:1.0.0 *?@author?pancm *?@date?2018年1月9日*/ public?interface?UserService?{/***?新增用戶*?@param?user*?@return*/boolean?addUser(User?user);/***?修改用戶*?@param?user*?@return*/boolean?updateUser(User?user);/***?刪除用戶*?@param?id*?@return*/boolean?deleteUser(int?id);/***?根據(jù)用戶名字查詢用戶信息*?@param?userName*/User?findUserByName(String?userName);/***?查詢所有*?@return*/List<User>?findAll(); }

實(shí)現(xiàn)類

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: *?用戶操作實(shí)現(xiàn)類 *?Version:1.0.0 *?@author?pancm *?@date?2018年1月9日*/ @Service public?class?UserServiceImpl?implements?UserService?{@Autowiredprivate?UserDao?userDao;@Overridepublic?boolean?addUser(User?user)?{boolean?flag=false;try{userDao.addUser(user);flag=true;}catch(Exception?e){e.printStackTrace();}return?flag;}@Overridepublic?boolean?updateUser(User?user)?{boolean?flag=false;try{userDao.updateUser(user);flag=true;}catch(Exception?e){e.printStackTrace();}return?flag;}@Overridepublic?boolean?deleteUser(int?id)?{boolean?flag=false;try{userDao.deleteUser(id);flag=true;}catch(Exception?e){e.printStackTrace();}return?flag;}@Overridepublic?User?findUserByName(String?userName)?{return?userDao.findByName(userName);}@Overridepublic?List<User>?findAll()?{return?userDao.findAll();} }

3.4 Controller 控制層

控制層這塊和springMVC很像,但是相比而言要簡(jiǎn)潔不少。說明:

  • RestController:默認(rèn)類中的方法都會(huì)以json的格式返回。

  • RequestMapping: 接口路徑配置。

  • method : 請(qǐng)求格式。

  • RequestParam: 請(qǐng)求參數(shù)。

具體實(shí)現(xiàn)如下:

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: *?用戶數(shù)據(jù)操作接口 *?Version:1.0.0 *?@author?pancm *?@date?2018年1月9日*/ @RestController @RequestMapping(value?=?"/api/user") public?class?UserRestController?{@Autowiredprivate?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("開始查詢所有數(shù)據(jù)...");return?userService.findAll();} }

3.5 Application 主程序

SpringApplication 則是用于從main方法啟動(dòng)Spring應(yīng)用的類。默認(rèn),它會(huì)執(zhí)行以下步驟:1.創(chuàng)建一個(gè)合適的ApplicationContext實(shí)例 (取決于classpath)。2.注冊(cè)一個(gè)CommandLinePropertySource,以便將命令行參數(shù)作為Spring properties。3.刷新application context,加載所有單例beans。4.激活所有CommandLineRunner beans。直接使用main啟動(dòng)該類,SpringBoot便自動(dòng)化配置了。ps:即使是現(xiàn)在我依舊覺得這個(gè)實(shí)在是太厲害了。

該類的一些注解說明。: SpringBootApplication:開啟組件掃描和自動(dòng)配置。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)?{//?啟動(dòng)嵌入式的?Tomcat?并初始化?Spring?環(huán)境及其各?Spring?組件SpringApplication.run(Application.class,?args);System.out.println("程序正在運(yùn)行...");} }

四、代碼測(cè)試

代碼編寫完之后,我們進(jìn)行代碼的測(cè)試。啟動(dòng)Application 之后,使用postman工具進(jìn)行接口的測(cè)試。postman的使用教程可以看我的博客: http://www.panchengming.com/2017/04/24/pancm12/

測(cè)試結(jié)果如下:

這里只使用了一個(gè)get和post測(cè)試,實(shí)際方法都測(cè)試過了,但是感覺沒必要貼圖了。項(xiàng)目我放到github上面去了: https://github.com/xuwujing/springBoot

總結(jié)

以上是生活随笔為你收集整理的基于 Spring Boot 的 Restful 风格实现增删改查的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。