SpringBoot使用MyBatis實現數據的CRUD
本篇博客將通過 MyBatis 來實現常用的數據增加、刪除、修改、查詢和分頁功能。

1.創(chuàng)建項目 & 引入依賴
創(chuàng)建一個 Spring Boot 項目,并引入 MyBatis 和 MySQL 依賴。
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.0.0</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies>
2.實現數據表的自動初始化
在項目的 resources 目錄下新建 db 目錄,并添加 schema.sql 文件,然后在此文件中寫入創(chuàng)建 user 表的 SQL 語句,以便進行初始化數據表。具體代碼如下:
DROP TABLE IF EXISTS `user`; CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) DEFAULT NULL, `age` int(11) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
在 application.properties 配置文件中配置數據庫連接,并加上數據表初始化的配置。具體代碼如下:
spring.datasource.initialize=true spring.datasource.initialization-mode=always spring.datasource.schema=classpath:db/schema.sql
完整的 application.properties 文件如下:
spring.datasource.url=jdbc:mysql://127.0.0.1/book?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useSSL=true spring.datasource.username=xxxx spring.datasource.password=xxxxxx spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.jpa.properties.hibernate.hbm2ddl.auto=update spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect spring.jpa.show-sql=true spring.datasource.initialization-mode=always spring.datasource.schema=classpath:db/schema.sql spring.thymeleaf.cache=false server.port=8080
這樣,Spring Boot 在啟動時就會自動創(chuàng)建 user 表。
3.實現實體對象建模
用 MyBatis 來創(chuàng)建實體,見以下代碼:
package com.example.demo.entity;
import lombok.Data;
@Data
public class User {
private int id;
private String name;
private int age;
}
從上述代碼可以看出,用 MyBatis 創(chuàng)建實體是不需要添加注解 @Entity 的,因為 @Entity 屬于 JPA 的專屬注解。
4.實現實體和數據表的映射關系
實現實體和數據表的映射關系可以在 Mapper 類上添加注解 @Mapper,見以下代碼。建議以后直接在入口類加 @MapperScan("com.example.demo.mapper"),如果對每個 Mapper 都加注解則很麻煩。
package com.example.demo.mapper;
import com.example.demo.entity.User;
import com.github.pagehelper.Page;
import org.apache.ibatis.annotations.*;
import java.util.List;
@Mapper
public interface UserMapper {
@Select("SELECT * FROM user WHERE id = #{id}")
User queryById(@Param("id") int id);
@Select("SELECT * FROM user")
List<User> queryAll();
@Insert({"INSERT INTO user(name,age) VALUES(#{name},#{age})"})
int add(User user);
@Delete("DELETE FROM user WHERE id = #{id}")
int delById(int id);
@Update("UPDATE user SET name=#{name},age=#{age} WHERE id = #{id}")
int updateById(User user);
@Select("SELECT * FROM user")
Page<User> getUserList();
}
5.實現增加、刪除、修改和查詢功能
創(chuàng)建控制器實現操作數據的 API,見以下代碼:
package com.example.demo.controller;
import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
UserMapper userMapper;
@RequestMapping("/querybyid")
User queryById(int id) {
return userMapper.queryById(id);
}
@RequestMapping("/")
List<User> queryAll() {
return userMapper.queryAll();
}
@RequestMapping("/add")
String add(User user) {
return userMapper.add(user) == 1 ? "success" : "failed";
}
@RequestMapping("/updatebyid")
String updateById(User user) {
return userMapper.updateById(user) == 1 ? "success" : "failed";
}
@RequestMapping("/delbyid")
String delById(int id) {
return userMapper.delById(id) == 1 ? "success" : "failed";
}
}
- 啟動項目,訪問
http://localhost:8080/user/add?name=pp&age=20,會自動添加一個name=pp、age=20的數據。


- 訪問
http://localhost:8080/user/updatebyid?name=pipi&age=26&id=1,會實現對id=1的數據的更新,更新為name=pipi、age=26。

- 訪問
http://localhost:8080/user/querybyid?id=1,可以查找到id=1的數據,此時的數據是name=pipi、age=26。

- 訪問
http://localhost:8080/user/,可以查詢出所有的數據。

- 訪問
http://localhost:8080/user/delbyid?id=1,可以刪除id為1的數據。

6.配置分頁功能
6.1 增加分頁支持
分頁功能可以通過 PageHelper 來實現。要使用 PageHelper,則需要添加如下依賴,并增加 Thymeleaf 支持。
<!-- 增加對PageHelper的支持 --> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>4.1.6</version> </dependency> <!--增加thymeleaf支持--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
6.2 創(chuàng)建分頁配置類
創(chuàng)建分頁配置類來實現分頁的配置,見以下代碼:
package com.example.demo.config;
import com.github.pagehelper.PageHelper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Properties;
@Configuration
public class PageHelperConfig {
@Bean
public PageHelper pageHelper(){
PageHelper pageHelper = new PageHelper();
Properties p = new Properties();
p.setProperty("offsetAsPageNum", "true");
p.setProperty("rowBoundsWithCount", "true");
p.setProperty("reasonable", "true");
pageHelper.setProperties(p);
return pageHelper;
}
}
代碼解釋如下。
@Configuration:表示 PageHelperConfig 這個類是用來做配置的。@Bean:表示啟動 PageHelper 攔截器。offsetAsPageNum:設置為true時,會將 RowBounds 第一個參數offset當成pageNum頁碼使用。rowBoundsWithCount:設置為true時,使用 RowBounds 分頁會進行count查詢。reasonable:啟用合理化時,如果pageNum<1會查詢第一頁,如果pageNum>pages會查詢最后一頁。
7.實現分頁控制器
創(chuàng)建分頁列表控制器,用以顯示分頁頁面,見以下代碼:
package com.example.demo.controller;
import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
@Controller
public class UserListController {
@Autowired
UserMapper userMapper;
@RequestMapping("/listall")
public String listCategory(Model m, @RequestParam(value="start", defaultValue="0")int start, @RequestParam(value="size", defaultValue="5") int size) throws Exception {
PageHelper.startPage(start,size,"id desc");
List<User> cs = userMapper.queryAll();
PageInfo<User> page = new PageInfo<>(cs);
m.addAttribute("page", page);
return "list";
}
}
start:在參數里接收當前是第幾頁。默認值是0。size:每頁顯示多少條數據。默認值是5。PageHelper.startPage(start,size,"id desc"): 根據start、size進行分頁,并且設置id倒排序。List<User>:返回當前分頁的集合。PageInfo<User>:根據返回的集合創(chuàng)建 Pagelnfo 對象。model.addAttribute("page", page):把page(PageInfo對象)傳遞給視圖,以供后續(xù)顯示。
8.創(chuàng)建分頁視圖
接下來,創(chuàng)建用于視圖顯示的 list.html,其路徑為 resources/template/list.html。
在視圖中,通過 page.pageNum 獲取當前頁碼,通過 page.pages 獲取總頁碼數,見以下代碼:
<div class="with:80%">
<div th:each="u : ${page.list}">
<span scope="row" th:text="${u.id}">id</span>
<span th:text="${u.name}">name</span>
</div>
</div>
<div>
<a th:href="@{listall?start=1}" rel="external nofollow" >[首頁]</a>
<a th:href="@{/listall(start=${page.pageNum-1})}" rel="external nofollow" rel="external nofollow" >[上頁]</a>
<a th:href="@{/listall(start=${page.pageNum+1})}" rel="external nofollow" rel="external nofollow" >[下頁]</a>
<a th:href="@{/listall(start=${page.pages})}" rel="external nofollow" rel="external nofollow" >[末頁]</a>
<div>當前頁/總頁數:<a th:text="${page.pageNum}" th:href="@{/listall(start=${page.pageNum})}" rel="external nofollow" ></a>
/<a th:text="${page.pages}" th:href="@{/listall(start=${page.pages})}" rel="external nofollow" rel="external nofollow" ></a></div>
</div>
啟動項目,多次訪問 http://localhost:8080/user/add?name=pp&age=26 增加數據,然后訪問 http://localhost:8080/listall 可以查看到分頁列表。

但是,上述代碼有一個缺陷:顯示分頁處無論數據多少都會顯示“上頁、下頁”。所以,需要通過以下代碼加入判斷,如果沒有上頁或下頁則不顯示。
<a th:if="${not page.IsFirstPage}" th:href="@{/listall(start=${page.pageNum-1})}" rel="external nofollow" rel="external nofollow" >[上頁]</a>
<a th:if="${not page.IsLastPage}" th:href="@{/listall(start=${page.pageNum+1})}" rel="external nofollow" rel="external nofollow" >[下頁]</a>
上述代碼的作用是:如果是第一頁,則不顯示“上頁”;如果是最后一頁,則不顯示“下頁”。


還有一種更簡單的方法:在 Mapper 中直接返回 page 對象,見以下代碼:
@Select("SELECT * FROM user")
Page<User> getUserList();
然后在控制器中這樣使用:
package com.example.demo.controller;
import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserListControllerB {
@Autowired
UserMapper userMapper;
// http://localhost:8080/listall2?pageNum=1&pageSize=2
@RequestMapping("/listall2")
// 如果方法的參數不指定默認值,且請求地址也沒有指定參數值,則項目運行時會報錯。
public Page<User> getUserList(@RequestParam(value="pageNum",defaultValue="0")int pageNum, @RequestParam(value = "pageSize", defaultValue = "5") int pageSize)
//public Page<User> getUserList(Integer pageNum, Integer pageSize)
{
PageHelper.startPage(pageNum, pageSize);
Page<User> userList= userMapper.getUserList();
return userList;
}
}
代碼解釋如下。
pageNum:頁碼。pageSize:每頁顯示多少記錄。

以上就是SpringBoot使用MyBatis實現數據的CRUD的詳細內容,更多關于SpringBoot MyBatis數據CRUD的資料請關注腳本之家其它相關文章!
- SpringBoot整合MyBatis實現CRUD操作項目實踐
- SpringBoot整合MyBatis Plus實現基本CRUD與高級功能
- SpringBoot之整合MyBatis實現CRUD方式
- SpringBoot整合Mybatis Plus實現基本CRUD的示例代碼
- springboot+mybatis-plus實現內置的CRUD使用詳解
- SpringBoot+Mybatis+Vue 實現商品模塊的crud操作
- 詳解springboot+mybatis-plue實現內置的CRUD使用詳情
- SpringBoot整合Mybatis實現CRUD
- Spring Boot整合MyBatis-Plus實現CRUD操作的示例代碼
相關文章
關于controller的異常處理及service層的事務控制方式
這篇文章主要介紹了關于controller的異常處理及service層的事務控制方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-02-02
Intellj?idea新建的java源文件夾不是藍色的圖文解決辦法
idea打開java項目后新建的模塊中,java文件夾需要變成藍色,這篇文章主要給大家介紹了關于Intellj?idea新建的java源文件夾不是藍色的相關資料,文中通過圖文介紹的非常詳細,需要的朋友可以參考下2024-02-02
Spring中@ControllerAdvice注解的用法解析
這篇文章主要介紹了Spring中@ControllerAdvice注解的用法解析,顧名思義,@ControllerAdvice就是@Controller 的增強版,@ControllerAdvice主要用來處理全局數據,一般搭配@ExceptionHandler、@ModelAttribute以及@InitBinder使用,需要的朋友可以參考下2023-10-10

