Rumah > Java > javaTutorial > Apakah kaedah untuk java SpringBoot untuk menyepadukan MyBatisPlus?

Apakah kaedah untuk java SpringBoot untuk menyepadukan MyBatisPlus?

WBOY
Lepaskan: 2023-05-10 23:34:04
ke hadapan
939 orang telah melayarinya

1. Apakah pendawaian automatik springboot?

Pemasangan automatik ialah teras springboot Secara umumnya, pemasangan automatik akan dikaitkan dengan springboot. Malah, Spring Framework telah pun melaksanakan fungsi ini. Spring Boot hanya mengoptimumkannya lagi melalui SPI.

SpringBoot mentakrifkan satu set spesifikasi antara muka Set spesifikasi ini menetapkan bahawa SpringBoot akan mengimbas fail META-INF/spring.factories dalam pakej balang rujukan luaran semasa permulaan dan memuatkan maklumat jenis yang dikonfigurasikan dalam fail ke dalam. Spring Container (ini melibatkan mekanisme pemuatan kelas JVM dan pengetahuan kontena Spring), dan melaksanakan pelbagai operasi yang ditakrifkan dalam kelas. Untuk balang luaran, anda hanya perlu mengikut piawaian yang ditakrifkan oleh SpringBoot untuk memasang fungsi anda sendiri ke dalam SpringBoot

2 anotasi springboot:

@EnableAutoConfiguration: Skop pakej imbasan secara lalai kepada kelas semasa.
@ComponentScan(" ") Skop pengimbasan pakej lalai kepada semua kelas di bawah keseluruhan pakej di mana kelas semasa berada.
Julat pengimbasan pakej lebih besar daripada @EnableAutoConfiguration dan @ComponentScan(" ") bergantung pada @EnableAutoConfiguration untuk memulakan program.
@EnableAutoConfiguration
@ComponentScan("Pakej pihak ketiga")
app.run()
@SpringBootApplication mengimbas julat pakej pakej adik beradik dan pakej semasa.
Lapisan bawah @SpringBootApplication adalah bersamaan dengan @EnableAutoConfiguration+@ComponentScan. Jangan imbas pakej pihak ketiga

3 Springboot menyepadukan mybatisplus untuk melaksanakan penambahan, pemadaman, pengubahsuaian dan pertanyaan

1 pertama import kebergantungan

   <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>
Salin selepas log masuk

2 jadual data dan tambah 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 (&#39;c001&#39;, &#39;家电&#39;);
INSERT INTO `category` VALUES (&#39;c002&#39;, &#39;鞋服&#39;);
INSERT INTO `category` VALUES (&#39;c003&#39;, &#39;化妆品&#39;);
INSERT INTO `category` VALUES (&#39;c004&#39;, &#39;汽车&#39;);

-- ----------------------------
-- 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 (&#39;p001&#39;, &#39;小\r\n米电视 机&#39;, 5000, &#39;1&#39;, &#39;c001&#39;);
INSERT INTO `products` VALUES (&#39;p002&#39;, &#39;格\r\n力空调&#39;, 3000, &#39;1&#39;, &#39;c001&#39;);
INSERT INTO `products` VALUES (&#39;p003&#39;, &#39;美\r\n的冰箱&#39;, 4500, &#39;1&#39;, &#39;c001&#39;);
INSERT INTO `products` VALUES (&#39;p004&#39;, &#39;篮\r\n球鞋&#39;, 800, &#39;1&#39;, &#39;c002&#39;);
INSERT INTO `products` VALUES (&#39;p005&#39;, &#39;运\r\n动裤&#39;, 200, &#39;1&#39;, &#39;c002&#39;);
INSERT INTO `products` VALUES (&#39;p006&#39;, &#39;T\r\n恤&#39;, 300, &#39;1&#39;, &#39;c002&#39;);
INSERT INTO `products` VALUES (&#39;p009&#39;, &#39;篮球&#39;, 188, &#39;1&#39;, &#39;c002&#39;);
Salin selepas log masuk

3 Cipta direktori berikut dalam projek

java SpringBoot整合MyBatisPlus的方法是什么

4. Cipta aplikasi.propertis di bawah sumber dan konfigurasikan sumber data

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
Salin selepas log masuk

5. Cipta kelas entiti di bawah 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;
}
Salin selepas log masuk

6. Cipta antara muka ProductDao di bawah lapisan dao Memandangkan mybatisplus merangkumkan penambahan, pemadaman, pengubahsuaian dan pertanyaan bagi satu jadual, semua anda yang perlu dilakukan ialah mewarisi antara muka BaseMapper

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);
}
Salin selepas log masuk

7. Cipta 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>
Salin selepas log masuk

di bawah pemeta di bawah sumber 8. Uji dalam kelas ujian di bawah pakej ujian

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());//获取当前页的记录
    }
}
Salin selepas log masuk

9. Akhirnya jalankan kelas ujian

java SpringBoot整合MyBatisPlus的方法是什么

Ujian selesai

Atas ialah kandungan terperinci Apakah kaedah untuk java SpringBoot untuk menyepadukan MyBatisPlus?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Label berkaitan:
sumber:yisu.com
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan