最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringBoot使用MyBatis實現數據的CRUD

 更新時間:2024年11月20日 09:48:37   作者:G皮T  
MyBatis是一個輕量級的對象關系映射(Object-Relational Mapping,ORM)框架,它允許開發(fā)者通過編寫SQL動態(tài)查詢數據庫,而無需顯式地操作JDBC,對于增刪改查操作,MyBatis提供了一種基于XML或注解的方式來進行,本文介紹了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=ppage=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,可以刪除 id1 的數據。

在這里插入圖片描述

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") : 根據 startsize 進行分頁,并且設置 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的資料請關注腳本之家其它相關文章!

相關文章

  • 基于Struts文件上傳(FormFile)詳解

    基于Struts文件上傳(FormFile)詳解

    下面小編就為大家?guī)硪黄赟truts文件上傳(FormFile)詳解。小編覺得挺不錯的,現在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-08-08
  • 關于controller的異常處理及service層的事務控制方式

    關于controller的異常處理及service層的事務控制方式

    這篇文章主要介紹了關于controller的異常處理及service層的事務控制方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-02-02
  • springboot打包部署到linux服務器的方法

    springboot打包部署到linux服務器的方法

    這篇文章主要介紹了springboot打包部署到linux服務器的方法,通過實例代碼相結合的形式給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下
    2018-06-06
  • Java實現域名解析的示例詳解(附帶源碼)

    Java實現域名解析的示例詳解(附帶源碼)

    這篇文章將從理論到實踐和從代碼到測試,全方位地講解如何利用?Java?實現一個簡單的域名解析器,感興趣的小伙伴可以跟隨小編一起學習一下
    2025-03-03
  • springboot集成redis哨兵集群的實現示例

    springboot集成redis哨兵集群的實現示例

    本文主要介紹了springboot集成redis哨兵集群的實現示例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2023-08-08
  • JAVA實現第三方短信發(fā)送過程詳解

    JAVA實現第三方短信發(fā)送過程詳解

    這篇文章主要介紹了JAVA實現第三方短信發(fā)送過程詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2019-09-09
  • java如何動態(tài)的處理接口的返回數據

    java如何動態(tài)的處理接口的返回數據

    本文主要介紹了java如何動態(tài)的處理接口的返回數據,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2023-01-01
  • 深入理解Java中觀察者模式與委托的對比

    深入理解Java中觀察者模式與委托的對比

    這篇文章主要介紹了Java中觀察者模式與委托的對比,觀察者模式:定義了一種一對多的依賴關系,讓多個觀察者對象同時監(jiān)聽某一個主題對象,委托的實現簡單來講就是用反射來實現的,本文給大家介紹的非常詳細,需要的朋友可以參考下
    2022-05-05
  • Intellj?idea新建的java源文件夾不是藍色的圖文解決辦法

    Intellj?idea新建的java源文件夾不是藍色的圖文解決辦法

    idea打開java項目后新建的模塊中,java文件夾需要變成藍色,這篇文章主要給大家介紹了關于Intellj?idea新建的java源文件夾不是藍色的相關資料,文中通過圖文介紹的非常詳細,需要的朋友可以參考下
    2024-02-02
  • Spring中@ControllerAdvice注解的用法解析

    Spring中@ControllerAdvice注解的用法解析

    這篇文章主要介紹了Spring中@ControllerAdvice注解的用法解析,顧名思義,@ControllerAdvice就是@Controller 的增強版,@ControllerAdvice主要用來處理全局數據,一般搭配@ExceptionHandler、@ModelAttribute以及@InitBinder使用,需要的朋友可以參考下
    2023-10-10

最新評論

曲沃县| 慈利县| 道孚县| 塘沽区| 石景山区| 勐海县| 浦江县| 台南县| 泰来县| 漳浦县| 沭阳县| 南京市| 肥乡县| 柯坪县| 华容县| 永城市| 井冈山市| 蓬安县| 漯河市| 建湖县| 青神县| 虹口区| 晋江市| 金昌市| 郓城县| 拜城县| 韩城市| 奉化市| 邹城市| 江津市| 静乐县| 张家界市| 灌阳县| 门源| 重庆市| 容城县| 宿迁市| 登封市| 新野县| 宣恩县| 汶川县|