您好,登錄后才能下訂單哦!
本篇內容主要講解“java SpringBoot整合MyBatisPlus的方法是什么”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“java SpringBoot整合MyBatisPlus的方法是什么”吧!
自動裝配是springboot的核心,一般提到自動裝配就會和springboot聯系在一起。實際上 Spring Framework 早就實現了這個功能。Spring Boot 只是在其基礎上,通過 SPI 的方式,做了進一步優化。
SpringBoot 定義了一套接口規范,這套規范規定:SpringBoot 在啟動時會掃描外部引用 jar 包中的META-INF/spring.factories文件,將文件中配置的類型信息加載到 Spring 容器(此處涉及到 JVM 類加載機制與 Spring 的容器知識),并執行類中定義的各種操作。對于外部 jar 來說,只需要按照 SpringBoot 定義的標準,就能將自己的功能裝置進 SpringBoot
@EnableAutoConfiguration:掃包范圍默認當前類。
@ComponentScan(" “) 掃包范圍默認當前類所在的整個包下面所有類。
掃包范圍大于@EnableAutoConfiguration,@ComponentScan(” ")依賴于@EnableAutoConfiguration啟動程序。
@EnableAutoConfiguration
@ComponentScan("第三方包 ")
app.run()
@SpringBootApplication 掃包范圍同級包和當前包。
@SpringBootApplication 底層等同于@EnableAutoConfiguration+@ComponentScan。不掃描第三方包
1.首先導入相關依賴
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.5.1</version> </dependency> <dependency> <groupId>com.spring4all</groupId> <artifactId>swagger-spring-boot-starter</artifactId> <version>1.9.1.RELEASE</version> </dependency> <dependency> <groupId>com.github.xiaoymin</groupId> <artifactId>swagger-bootstrap-ui</artifactId> <version>1.7.8</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </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.創建數據表并添加數據
DROP TABLE IF EXISTS `category`; CREATE TABLE `category` ( `cid` varchar(32) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL, `cname` varchar(50) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL, PRIMARY KEY (`cid`) USING BTREE ) ENGINE = InnoDB CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci ROW_FORMAT = DYNAMIC; -- ---------------------------- -- Records of category -- ---------------------------- INSERT INTO `category` VALUES ('c001', '家電'); INSERT INTO `category` VALUES ('c002', '鞋服'); INSERT INTO `category` VALUES ('c003', '化妝品'); INSERT INTO `category` VALUES ('c004', '汽車'); -- ---------------------------- -- Table structure for products -- ---------------------------- DROP TABLE IF EXISTS `products`; CREATE TABLE `products` ( `pid` varchar(32) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL, `pname` varchar(50) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL, `price` int NULL DEFAULT NULL, `flag` varchar(2) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL, `category_id` varchar(32) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NULL DEFAULT NULL, PRIMARY KEY (`pid`) USING BTREE, INDEX `category_id`(`category_id`) USING BTREE, CONSTRAINT `products_ibfk_1` FOREIGN KEY (`category_id`) REFERENCES `category` (`cid`) ON DELETE RESTRICT ON UPDATE RESTRICT ) ENGINE = InnoDB CHARACTER SET = utf8mb3 COLLATE = utf8mb3_general_ci ROW_FORMAT = DYNAMIC; -- ---------------------------- -- Records of products -- ---------------------------- INSERT INTO `products` VALUES ('p001', '小\r\n米電視 機', 5000, '1', 'c001'); INSERT INTO `products` VALUES ('p002', '格\r\n力空調', 3000, '1', 'c001'); INSERT INTO `products` VALUES ('p003', '美\r\n的冰箱', 4500, '1', 'c001'); INSERT INTO `products` VALUES ('p004', '籃\r\n球鞋', 800, '1', 'c002'); INSERT INTO `products` VALUES ('p005', '運\r\n動褲', 200, '1', 'c002'); INSERT INTO `products` VALUES ('p006', 'T\r\n恤', 300, '1', 'c002'); INSERT INTO `products` VALUES ('p009', '籃球', 188, '1', 'c002');
3.在項目中創建如下目錄
4.在resources下創建application.propertis并配置數據源
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.username=root spring.datasource.password=123456 spring.datasource.url=jdbc:mysql:///springboot #日志 mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl mybatis.mapper-locations=classpath:mapper/*.xml
5.在pojo下創建實體類
package com.azy.pojo; import java.io.Serializable; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; /** * products * @author */ @Data @AllArgsConstructor @NoArgsConstructor @TableName(value = "products") public class Products implements Serializable { @TableId(type = IdType.AUTO) private String pid; public Products(String pid, String pname, Integer price) { this.pid = pid; this.pname = pname; this.price = price; } private String pname; private Integer price; private String flag; private String category_id; @TableField(exist = false) private Category category; private static final long serialVersionUID = 1L; }
6.在dao層下創建ProductDao這個接口,由于mybatisplus封裝了單表的增刪改查,所有只需繼承BaseMapper這個接口就ok
package com.azy.dao; import com.azy.pojo.Products; import com.baomidou.mybatisplus.core.conditions.Wrapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.core.metadata.IPage; import org.apache.ibatis.annotations.Param; /** * @ fileName:ProductsDao * @ description: * @ author:Azy * @ createTime:2023/4/11 18:57 * @ version:1.0.0 */ public interface ProductsDao extends BaseMapper<Products> { IPage<Products> findPage(IPage<Products> iPage, @Param("ew") Wrapper<Products> wrapper); }
7.在resources下面的mapper下創建ProductsDao.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 namespace="com.azy.dao.ProductsDao"> <resultMap id="ProductsMap" type="com.azy.pojo.Products" autoMapping="true"> <id property="pid" column="pid" jdbcType="VARCHAR"/> <result property="pname" column="pname" jdbcType="VARCHAR"/> <result property="price" column="price" jdbcType="INTEGER"/> <result property="flag" column="flag" jdbcType="VARCHAR"/> <result property="category_id" column="category_id" jdbcType="VARCHAR"/> <association property="category" javaType="com.azy.pojo.Category" autoMapping="true"> <id column="cid" property="cid" jdbcType="VARCHAR"/> <result property="cname" column="cname" jdbcType="VARCHAR"/> </association> </resultMap> <select id="findPage" resultType="com.azy.pojo.Products" resultMap="ProductsMap"> select * from products p join category c on p.category_id=c.cid <if test="ew!=null"> <where> ${ew.sqlSegment} </where> </if> </select> </mapper>
8.在test包下的測試類中測試
package com.azy; import com.azy.dao.ProductsDao; import com.azy.dao.UserDao; import com.azy.pojo.Products; import com.azy.pojo.User; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import javax.annotation.Resource; import java.util.List; @SpringBootTest class DemoApplicationTests { @Resource private UserDao userDao; @Test void contextLoads() { QueryWrapper<User> wrapper = new QueryWrapper<>(); wrapper.likeRight("name","_z"); wrapper.or(); wrapper.between("age",10,20); wrapper.orderByDesc("age"); wrapper.select("name","age"); List<User> users = userDao.selectList(wrapper); users.forEach(System.out::println); } @Test public void delete(){ System.out.println(userDao.deleteById(5)); } @Test public void insert(){ User user = new User(); user.setAge(18); user.setName("cxk"); user.setEmail("123@qq.com"); System.out.println(userDao.insert(user)); } @Test public void update(){ User user = new User(); user.setAge(19); user.setName("azy"); user.setEmail("321@qq.com"); user.setId(6L); System.out.println(userDao.updateById(user)); } @Test public void selectById(){ System.out.println(userDao.selectById(4)); } @Test public void testPage(){ Page<User> page = new Page<>(1, 3);//current:當前第幾頁 size:每頁顯示條數 userDao.selectPage(page,null);//把查詢分頁的結構封裝到page對象中 System.out.println("當前頁的記錄"+page.getRecords());//獲取當前頁的記錄 System.out.println("獲取總頁數"+page.getPages());//獲取當前頁的總頁數 System.out.println("獲取總條數"+page.getTotal());//獲取當前頁的記錄 } // ============================================================== @Resource private ProductsDao productsDao; @Test public void testQueryProductById(){ System.out.println(productsDao.selectById("p008")); } @Test public void testDelete(){ System.out.println(productsDao.deleteById("p008")); } @Test public void testInsert(){ Products products = new Products(); products.setPname("滑板鞋"); products.setFlag("2"); products.setPrice(8888); products.setCategory_id("c002"); products.setPid("p009"); System.out.println(productsDao.insert(products)); } @Test public void testUpdate(){ Products products = new Products(); products.setPname("籃球"); products.setFlag("1"); products.setPrice(188); products.setCategory_id("c002"); products.setPid("p009"); System.out.println(productsDao.updateById(products)); } @Test public void testProductsPage(){ Page<Products> page = new Page<>(1, 3);//current:當前第幾頁 size:每頁顯示條數 productsDao.selectPage(page,null);//把查詢分頁的結構封裝到page對象中 System.out.println("當前頁的記錄"+page.getRecords());//獲取當前頁的記錄 System.out.println("獲取總頁數"+page.getPages());//獲取當前頁的總頁數 System.out.println("獲取總條數"+page.getTotal());//獲取當前頁的記錄 } @Test public void testProductsPage2(){ Page<Products> page=new Page<>(1,3); QueryWrapper<Products> wrapper=new QueryWrapper<>(); wrapper.gt("price",1000); productsDao.findPage(page,wrapper); System.out.println("當前頁的記錄"+page.getRecords());//獲取當前頁的記錄 System.out.println("獲取總頁數"+page.getPages());//獲取當前頁的記錄 System.out.println("獲取總條數"+page.getTotal());//獲取當前頁的記錄 } }
9.最后運行測試類
測試完成
到此,相信大家對“java SpringBoot整合MyBatisPlus的方法是什么”有了更深的了解,不妨來實際操作一番吧!這里是億速云網站,更多相關內容可以進入相關頻道進行查詢,關注我們,繼續學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。