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

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

SpingBoot中使用MyBatis和pagehelper实现数据的增删改查和分页

發(fā)布時間:2025/4/5 编程问答 46 豆豆
生活随笔 收集整理的這篇文章主要介紹了 SpingBoot中使用MyBatis和pagehelper实现数据的增删改查和分页 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

文章目錄

    • 一.認識MyBatis
        • CRUD注解
        • 映射注解
        • 高級注解
    • 二.用MyBatis實現(xiàn)數(shù)據(jù)的增加、刪除、修改、查詢和分頁
      • 1.創(chuàng)建springboot項目并引入依賴
      • 2.實現(xiàn)數(shù)據(jù)表的自動初始化
      • 3.實現(xiàn)實體對象建模
      • 4.實現(xiàn)實體和數(shù)據(jù)表的映射關系
      • 5.實現(xiàn)增加、刪除、修改和查詢功能
      • 實驗結(jié)果
      • 6.配置分頁功能
      • 7實現(xiàn)分頁控制器
      • 8創(chuàng)建分頁視圖
      • 9啟動類添加@ComponentScan

一.認識MyBatis

MyBatis是一款優(yōu)秀的持久層框架,它支持定制化SQL、存儲過程,以及高級映射。它可以使用簡單的XML或注解來配置和映射原生信息,將接口和JAVA的POJOS(Plain Old Java Objects,普通的Java對象)映射成數(shù)據(jù)庫中的記錄。

MyBatis 3 提供的注解可以取代XML。例如,使用注解@Select直接編寫SQL完成數(shù)據(jù)查詢;使用高級注解@SelectProvider還可以編寫動態(tài)SQL,以應對復雜的業(yè)務需求。

CRUD注解

增加、刪除、修改和查詢時主要的業(yè)務操作,必須掌握這些基礎注解的使用方法。MyBatis提供的操作數(shù)據(jù)的基礎注解有以下4個

  • @Select:用于構(gòu)建查詢語句
  • @Insert:用于構(gòu)建添加語句
  • @Update:用于構(gòu)建修改語句
  • @Delete:用于構(gòu)建刪除語句

具體使用如下
從代碼中可以看出:首先使用@Mapper注解來標注類,把UserMapper這個DAO交給Spring管理。這樣Spring會自動生成一個實現(xiàn)類,不用再寫UserMapper的映射文件了。最后使用基礎的CRUD注解來添加要實現(xiàn)的功能。

//添加了@Mapper注解之后這個接口在編譯時會生成相應的實現(xiàn)類 @Mapper public interface UserMapper{@Select("SELECT * FROM user WHERE id=#{id}")User queryByld(@Param("id") int id);@Select("SELECT * FROM user limit 1000")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 limit 1000")Page<User> getUserList(); }

映射注解

MyBatis的映射注解用于建立實體和關系的映射。它有以下3個注解。

  • @Results:用于填寫結(jié)果集的多個字段的映射關系
  • @Result:用于填寫結(jié)果集的單個字段的映射關系
  • @ResultMap:根據(jù)ID關聯(lián)XML里面的 < resultMap>

可以在查詢SQL的基礎上,指定返回的結(jié)果集的映射關系。其中,property表示實體對象的屬性名,column表示對應的數(shù)據(jù)庫字段名。使用方法如下

@Result({@Result(property="username",column="USERNAME");@Result(property="password",column="PASSWORD");})@Select("select * from user limit 1000") List<User> list();

高級注解

MaBatis 3.x版本主要提供了以下4個CRUD的高級注解

  • @SelectProvider:用于構(gòu)建動態(tài)查詢SQL
  • @InsertProvider:用于構(gòu)建動態(tài)添加SQL
  • @UpdateProvider:用于構(gòu)建動態(tài)更新SQL
  • @DeleteProvider:用于構(gòu)建動態(tài)刪除SQL

高級注解主要用于編寫動態(tài)SQL。這里以@SelectProvider為例,它主要包含兩個注解屬性,其中,type表示工具類,method表示工具類的某個方法(用于返回具體的SQL)。

以下代碼可以構(gòu)建動態(tài)SQL,實現(xiàn)查詢功能:

@Mapper public interface UserMapper{@SelectProvider(type=UserSql.class,method="listAll") List<User> listAllUser(); }

UserSql工具類的代碼如下

public class UserSql{public String listAll(){return "select * from user limit 1000";} }

二.用MyBatis實現(xiàn)數(shù)據(jù)的增加、刪除、修改、查詢和分頁

分為兩部分:數(shù)據(jù)增刪改和分頁
全部(兩部分合起來)的項目結(jié)構(gòu)如下

1.創(chuàng)建springboot項目并引入依賴

引入MyBatis,Mysql,pagehelper.Thymeleaf等依賴

<dependency><groupId>com.github.pagehelper</groupId><artifactId>pagehelper</artifactId><version>5.1.2</version></dependency><dependency><groupId>com.github.pagehelper</groupId><artifactId>pagehelper-spring-boot-starter</artifactId><version>1.2.3</version></dependency><dependency><groupId>com.github.pagehelper</groupId><artifactId>pagehelper-spring-boot-autoconfigure</artifactId><version>1.2.3</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId></dependency><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.0.0</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.20</version><scope>runtime</scope></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency>

并且添加配置文件application.properties
數(shù)據(jù)庫連接并加上數(shù)據(jù)表初始化的配置

spring.datasource.url=jdbc:mysql://127.0.0.1/book?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useSSL=true spring.datasource.username=root spring.datasource.password=root spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driverspring.jpa.properties.hibernate.hbm2ddl.auto=update spring.jpa.proterties.hibernate.dialect=org.hibernate.dialect.MYSQL5InnoDBDialect spring.datasource.initialization-mode=always spring.datasource.schema=classpath:db/schema.sql

2.實現(xiàn)數(shù)據(jù)表的自動初始化

在項目的resource目錄下新建db目錄,并添加schema.sql文件,然后再此文件中寫入創(chuàng)建user表的sql語句,以便進行初始化數(shù)據(jù)表

DROP TABLE IF EXISTS user; --IF object_id('user','U') is not NULL drop table '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;

另外還有一個問題:sql語句是不區(qū)分大小寫的,但是,編譯的時候,操作系統(tǒng)會將所有字符轉(zhuǎn)換成大寫的,再進行編譯。如果大寫,在編譯的時候,可以節(jié)省轉(zhuǎn)化的時間。當SQL語句很多的時候,大寫就顯得很重要了。在大型的ERP系統(tǒng)開發(fā)的時候,往往會要求大寫。

3.實現(xiàn)實體對象建模

用MyBatis來創(chuàng)建實體
從代碼中可以看出,用MyBatis創(chuàng)建實體不需要添加注解@Entity,因為@Entity是屬于JPA的專屬注解

User.java

package com.example.demo.entity;import lombok.Data; @Data public class User {private int id;private String name;private int age; }

4.實現(xiàn)實體和數(shù)據(jù)表的映射關系

實現(xiàn)實體和數(shù)據(jù)表的映射關系可以在Mapper類上添加注解@Mapper
UserMapper.java

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); }

5.實現(xiàn)增加、刪除、修改和查詢功能

創(chuàng)建控制器實現(xiàn)操作數(shù)據(jù)的API
UserController.java

package com.example.demo.controller;import com.example.demo.entity.User; import com.example.demo.controller.UserController; 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.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController;import java.util.List;@RestController @RequestMapping("/user") public class UserController {@AutowiredUserMapper 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?"sources":"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";} }

完成這一步,便可以啟動項目,并且進行下面的操作,得到實驗結(jié)果。

實驗結(jié)果

啟動項目,訪問如下鏈接http://localhost:8080/user/add?name=hello&age=10,會自動添加一個名為name=hello,age=10的數(shù)據(jù),以此類推

訪問http://localhost:8080/user/,可以查詢出所有的數(shù)據(jù)

訪問http://localhost:8080/user/querybyid?id=3,可以查找到id=3的數(shù)據(jù),

同樣的,可以在數(shù)據(jù)庫中查看

6.配置分頁功能

分頁功能通過PageHelper來實現(xiàn),上面已經(jīng)添加過依賴(共有三個關于pagehelper的依賴),還需要Thymeleaf依賴

創(chuàng)建分頁配置類
pageHelperConfig.java
注解@Configuration表示這個類是用來做配置的

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 {@Beanpublic PageHelper pageHelper(){PageHelper pageHelper = new PageHelper();Properties p = new Properties();//1.offsetAsPageNum:設置為true時,會將RowBounds第一個參數(shù)offset當成pageNum頁碼使用.p.setProperty("offsetAsPageNum", "true");//2.rowBoundsWithCount:設置為true時,使用RowBounds分頁會進行count查詢.p.setProperty("rowBoundsWithCount", "true");//3.reasonable:啟用合理化時,如果pageNum<1會查詢第一頁,如果pageNum>pages會查詢最后一頁。p.setProperty("reasonable", "true");pageHelper.setProperties(p);return pageHelper;} }

7實現(xiàn)分頁控制器

用以顯示分頁頁面
UserListController.java

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;@Controllerpublic class UserListController {@AutowiredUserMapper userMapper;@RequestMapping("/listall")public String listCategory(Model m,@RequestParam(value="start",defaultValue = "0")int start,@RequestParam(value = "size",defaultValue = "20")int size) throws Exception{PageHelper.startPage(start,size);List<User> cs=userMapper.queryAll();PageInfo<User> page=new PageInfo<>(cs);m.addAttribute("page",page);return "list";} }

8創(chuàng)建分頁視圖

這是前端的內(nèi)容,創(chuàng)建list.html,路徑是resources/templates/list.html

list.html

<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head><meta charset="UTF-8"><title>hello的web</title> </head> <body> <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}">[首頁]</a><a th:if="${not page.IsFirstPage}" th:href="@{/listall(start=${page.pageNum-1})}">[上頁]</a><a th:if="${not page.IsLastPage}" th:href="@{/listall(start=${page.pageNum+1})}">[下頁]</a><a th:href="@{/listall(start=${page.pages})}">[末頁]</a><div>當前頁/總頁數(shù):<a th:text="${page.pageNum}" th:href="@{/listall(start=${page.pageNum})}"></a>/<a th:text="${page.pages}" th:href="@{/listall(start=${page.pages})}"></a></div></div></body> </html>

9啟動類添加@ComponentScan

package com.example.demo;import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan;//@MapperScan("com.example.demo.mapper") //可以使用:basePackageClasses={},basePackages={} @ComponentScan(basePackages={"com.example.demo.mapper","com.example.demo.controller"})@SpringBootApplication public class MybatisCurdPageApplication {public static void main(String[] args) {SpringApplication.run(MybatisCurdPageApplication.class, args);}}

啟動項目,首先通過訪問http://localhost:8080/listall得到下面的界面


然后通過訪問http://localhost:8080/user/add?name=hello&age=10,并且多次刷新(最好20次以上),這是為user表添加用戶信息,用于后面的分頁顯示

再次輸入網(wǎng)址http://localhost:8080/listall
可以看到分頁

總結(jié)

以上是生活随笔為你收集整理的SpingBoot中使用MyBatis和pagehelper实现数据的增删改查和分页的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

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