What is the method for java SpringBoot to integrate MyBatisPlus?
1.What is springboot automatic assembly?
Automatic assembly is the core of springboot. Generally speaking, automatic assembly will be associated with springboot. In fact, Spring Framework has already implemented this function. Spring Boot only further optimizes it through SPI.
SpringBoot defines a set of interface specifications. This set of specifications stipulates that: SpringBoot will scan the META-INF/spring.factories file in the external reference jar package at startup and load the type information configured in the file into Spring container (this involves JVM class loading mechanism and Spring's container knowledge), and perform various operations defined in the class. For external jars, you only need to follow the standards defined by SpringBoot to install your own functions into SpringBoot
2.springboot annotation:
@EnableAutoConfiguration: Scan package scope defaults to the current class.
@ComponentScan(" ") The package scanning scope defaults to all classes under the entire package where the current class is located.
The package scanning range is greater than @EnableAutoConfiguration, and @ComponentScan(" ") relies on @EnableAutoConfiguration to start the program.
@EnableAutoConfiguration
@ComponentScan("Third-party package ")
app.run()
@SpringBootApplication Scans the package range of sibling packages and the current package.
The bottom layer of @SpringBootApplication is equivalent to @EnableAutoConfiguration @ComponentScan. Do not scan third-party packages
3. Springboot integrates mybatisplus to implement addition, deletion, modification and query
1. First import relevant dependencies
<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. Create a data table and add data
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.Create the following directory in the project
4.Create application.propertis under resources and configure the data source
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.In Create an entity class under 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. Create the ProductDao interface under the dao layer. Since mybatisplus encapsulates the addition, deletion, modification and query of a single table, all you need to do is inherit the BaseMapper interface and it will be 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. Create 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>
under the mapper under resources 8. Test in the test class under the test package
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. Finally run the test class
Finished test
The above is the detailed content of What is the method for java SpringBoot to integrate MyBatisPlus?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.
