前面一篇文章介紹了SpringBoot項目的創建: Spring Boot(1)—創建并運行項目
這篇文章簡單介紹一下SpringBoot項目的增刪改查。
所需工具:IDEA、java1.8、mysql
0.創建項目
我們通過IDEA創建項目。
點擊”新建”—>”項目”

選擇“Spring Initializr” 選擇版本號1.8,然后點擊“下一步”

然后填寫必要信息。類型這個地方選擇Maven(Generate a Maven based project archive),語言選擇java,java版本我們這里選擇8。其余信息自定義。

然后選擇“web”,選擇“Spring web”然后選擇Spring Boot的版本號,這里線不建議選擇3.0及以上版本,我們選擇的是2.7.7,然后點擊“下一步”。

然后點擊“完成”

如果出現下面這樣,表示正常

如果出現下面這樣圖,不正常,可以參考下面的兩篇文章進行解決

參考解決辦法:
Project ‘org.springframework.boot:spring-boot-starter-parent:2.7.7’ not found
1.添加必要依賴
因為要實現增刪改查,所以要添加一些依賴,比如數據庫等
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.7.7</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>site.longkui</groupId> <artifactId>app</artifactId> <version>0.0.1-SNAPSHOT</version> <name>app</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </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-test</artifactId> <scope>test</scope> </dependency> <!-- mysql --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <!--mybatis --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.4</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
2.創建數據庫
參考下面這篇文章創建數據庫表: mysql生成數據
DROP TABLE IF EXISTS `students`; CREATE TABLE `students` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `stu_name` varchar(20) NOT NULL , `stu_sex` varchar(10) NOT NULL , `class_id` int(10) NOT NULL , `age` int(10) NOT NULL DEFAULT 18, `create_time` datetime NULL DEFAULT CURRENT_TIMESTAMP, `update_time` datetime NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=1000 DEFAULT CHARSET=utf8;
insert into students (stu_name,stu_sex,class_id,age) values ('張三','男',1001,18), ('王曉紅','女',2001,20), ('李清樂','男',1001,23), ('趙倚天','男',3001,23);
3.創建或修改配置文件
我們創建的springboot項目一般只有application.properties文件,如果沒有xxx.yml文件,我們需要自己創建這個文件。
在這里,我們創建application.yml文件(或者也同步創建application-dev.yml文件,關于這兩個文件的區別和優先級可以參考這篇文章:)
spring boot的application.yml和application-dev.yml
創建的application.yml內容參考如下:
server: port: 8082 # spring配置 spring: datasource: url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC username: root password: root driver-class-name: com.mysql.cj.jdbc.Driver # mybaits配置 mybatis: # 配置mapper的掃描,找到所有的mapper.xml映射文件 mapper-locations: classpath*:mappers/**/*Mapper.xml # 搜索指定包別名 type-aliases-package: site.longkui.**.entity

我們參考上面圖片新建五個文件夾,controller、entity、mapper、service、mappers。注意各自的位置,我們掃描包的時候需要用到位置。
這個地方主要說明的是
1.mysql的相關部分:
自己參考上面的腳本創建數據庫和表,數據庫連接和用戶名密碼等不要寫錯了。
2.mybatis的配置部分:
mapper-locations主要表示要映射的xml文件。按照上面的圖片的配置文件,mapper-locations可以寫成classpath*:mappers/*Mapper.xml這個地市之所以寫成classpath*:mappers/**/*Mapper.xml這樣主要是為了以后擴展,包括下面的type-aliases-package也是這個想法。
4.編寫xml和mapper層
我們創建訪問數據庫的增刪改查的xml文件,注意要在resources/mappers下面創建,而且創建的文件名稱一定要是 xxxMapper.xml。這是因為我們配置文件定義的這種格式,如果你寫的xml文件命名為abc.xml,根據上面的配置,spring就無法掃描到這個文件,也就不能執行這個文件中的sql。
(注:為了方(tou)便(lan),我們不創建實體類,不寫resultMap,直接用數據庫字段一一對應)
我們創建的xml文件參考如下
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!--必須和mapper里面一一對應--> <mapper namespace="site.longkui.app.mapper.StudentsMapper"> <!--查詢 --> <select id="getList" resultType="java.util.HashMap"> SELECT * from students </select> <!--刪除 --> <delete id="delById"> delete from students where id =#{id}; </delete> <!--新增--> <insert id="insertStudent"> INSERT INTO `students` (`stu_name`, `stu_sex`, `class_id`, `age`) VALUES ( #{stu_name}, #{stu_sex}, #{class_id}, #{age}); </insert> <!--更新--> <update id="updateStudent"> update students set stu_name=#{stu_name}, stu_sex=#{stu_sex}, class_id=#{class_id}, age=#{age} where id=#{id}; </update> </mapper>
然后Mapper層如下:
package site.longkui.app.mapper; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Repository; import java.util.HashMap; import java.util.List; @Repository public interface StudentsMapper { //查詢所有 List<HashMap<HashMap,HashMap>> getList(); //刪除一個 Boolean delById(@Param("id") int id); //新增一個 Boolean insertStudent(@Param("stu_name") String stu_name, @Param("stu_sex") String stu_sex, @Param("class_id") int class_id, @Param("age") int age); //更新 Boolean updateStudent(@Param("id") int id, @Param("stu_name") String stu_name, @Param("stu_sex") String stu_sex, @Param("class_id") int class_id, @Param("age") int age); }
5.service層
這個地方需要說明一下,本來這個層級關系一般是sevice層,然后寫service的實現層(impl),在實現層里去訪問Mapper層的代碼,但是這個demo沒有太復雜的邏輯,所以偷懶了一下,直接在service層去訪問Mapper層的代碼。
package site.longkui.app.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import site.longkui.app.mapper.StudentsMapper; import java.util.HashMap; import java.util.List; @Service public class StudentsService { @Autowired private StudentsMapper studentsMapper; //查詢所有 public List<HashMap<HashMap,HashMap>> getList(){ return studentsMapper.getList(); } //刪除一個 public Boolean delById(int id){ return studentsMapper.delById(id); } //新增一個 public Boolean insertStudent(String stu_name,String stu_sex,int class_id,int age){ return studentsMapper.insertStudent(stu_name, stu_sex, class_id, age); } //修改一個 public Boolean updateStudent(int id,String stu_name,String stu_sex,int class_id,int age){ return studentsMapper.updateStudent(id, stu_name, stu_sex, class_id, age); } }
6.controller層
package site.longkui.app.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import site.longkui.app.service.StudentsService; import java.util.HashMap; import java.util.List; @RestController @RequestMapping("/students") public class StudentsController { @Autowired private StudentsService studentsService; //查詢所有 @GetMapping("/getList") public List<HashMap<HashMap,HashMap>> getList(){ try { List<HashMap<HashMap,HashMap>>res = studentsService.getList(); return res; }catch (Exception e){ e.toString(); return null; } } //刪除一個 @GetMapping("/del/{id}") public Boolean delById(@PathVariable int id){ return studentsService.delById(id); } //新增一個 @GetMapping("/add/{stu_name}/{stu_sex}/{class_id}/{age}") public Boolean insertStudent(@PathVariable String stu_name, @PathVariable String stu_sex, @PathVariable int class_id, @PathVariable int age){ return studentsService.insertStudent(stu_name, stu_sex, class_id, age); } //更新一個 @GetMapping("/update/{id}/{stu_name}/{stu_sex}/{class_id}/{age}") public Boolean updateStudent(@PathVariable int id, @PathVariable String stu_name, @PathVariable String stu_sex, @PathVariable int class_id, @PathVariable int age){ return studentsService.updateStudent(id,stu_name, stu_sex, class_id, age); } }
需要說明的是,
- getList這個方法的返回值類型
List<HashMap<HashMap,HashMap>>
一般來說,我們都會用實體類來接受返回的數據,但是,本文這里又偷懶了,沒有寫實體類對應,直接用比較萬能的方式接收返回的數據,實際開發中并不建議這面用。
2. 非常明顯的可以看出,這里的增刪改查操作都是用的get方法,實際開發中一般是不允許這么干的,一般來說,只有查詢數據的時候用get方法,其余的用POST和PUT,本文只是為了偷懶,測試方便所以用的全都是get方法。
7.修改啟動類
我們找到啟動類的位置,加上MapperScan
package site.longkui.app; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication @MapperScan("site.longkui.**.mapper") public class AppApplication { public static void main(String[] args) { SpringApplication.run(AppApplication.class, args); } }
8.測試增刪改查
如果出現了:Whitelabel Error Page 報500,可以參考下面這篇文章嘗試一下:
1.查詢所有數據:
URL:http://localhost:8082/students/getList

2.刪除一個學生數據:
URL:http://localhost:8082/students/del/1000

然后去數據庫里查看,確實沒有了編號是1000的學生信息了。

3.新增一個學生:
URL: http://localhost:8080/studets/add/王老虎/男/5/19
這里沒有用API工具,因為這樣傳中文會有問題,我們用瀏覽器代替
上面這個請求就會轉換成:http://localhost:8082/students/add/%E7%8E%8B%E8%80%81%E8%99%8E/%E7%94%B7/5/19

然后,數據庫里也正常有數據了

4.更新一個學生
我們把王老虎的性別改成女
URL: http://localhost:8080/studets/update/1005/王老虎/女/5/19
瀏覽器會轉換成:
http://localhost:8082/students/update/1005/%E7%8E%8B%E8%80%81%E8%99%8E/%E5%A5%B3/5/19

然后去數據庫里查詢,發現王老虎的性別已經被修改了。

9.總結
本來覺得原理都懂,收搓一遍應該很簡單,但是做和說是兩碼事,真正試一試就能看出很多小問題了。