【Mybatis-Plus】Mybatis-Plus入门基础:


在这里插入图片描述

一、pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.10</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.kd</groupId>
    <artifactId>MyBatis-Plus</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>MyBatis-Plus</name>
    <description>MyBatis-Plus</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- MySQL驱动-->
        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- 连接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.17</version>
        </dependency>

        <!-- MyBatis-Plus -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.2</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
二、application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/store?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=root

#连接池配置
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.druid.initial-size=20
spring.datasource.druid.min-idle=10
spring.datasource.druid.max-active=100

#开启驼峰命名映射
mybatis-plus.configuration.map-underscore-to-camel-case=true

#输出SQL语句
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

#配置XML配置文件的位置
mybatis-plus.mapper-locations=classpath:mapper/*.xml

#配置XML映射文件中指定的实体类名路径
mybatis-plus.type-aliases-package=com.kd.mybatisplus.pojo
三、Product
package com.kd.mybatisplus.entity;

import com.baomidou.mybatisplus.annotation.*;
import lombok.Data;

import java.io.Serializable;
import java.util.Date;

@Data
@TableName("t_product") //当前实体类对应表的映射
public class Product implements Serializable {
    //@TableId(type = IdType.AUTO)  //id自增策略
    private Integer id;

    @TableField("category_id") //开启驼峰映射
    private Integer categoryId;

    @TableField("item_type")
    private String itemType;

    private String title;

    @TableField("sell_point")
    private String sellPoint;

    private Long price;
    private Integer num;
    private String image;
    private Integer status;
    private Integer priority;

    @TableField(value = "created_user", fill = FieldFill.INSERT)/*FieldFill.INSERT:只在插入数据时自动填充字段的值*/
    private String createdUser;

    @TableField(value = "created_time", fill = FieldFill.INSERT)
    private Date createdTime;

    @TableField(value = "modified_user", fill = FieldFill.INSERT_UPDATE)/*FieldFill.INSERT_UPDATE:在插入和更新数据时自动填充字段的值*/
    private String modifiedUser;

    @TableField(value = "modified_time", fill = FieldFill.INSERT_UPDATE)
    private Date modifiedTime;
}
四、ProductMapper
package com.kd.mybatisplus.mapper;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.kd.mybatisplus.entity.Product;
import org.apache.ibatis.annotations.Mapper;


@Mapper  /*将当前的接口对应的实现类交给mybatis工厂来创建*/
public interface ProductMapper extends BaseMapper<Product> {

}
五、MyMetaObjectHandler
package com.kd.mybatisplus.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 源数据对象处理器(设置实体类字段默认值的配置)
 */
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        // 自动填充创建时间和修改时间
        this.strictInsertFill(metaObject, "createdTime", Date.class, new Date());
        this.strictInsertFill(metaObject, "modifiedTime", Date.class, new Date());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.strictUpdateFill(metaObject, "modifiedTime", Date.class, new Date());
    }
}
六、所用案例:MyBatisPlusApplicationTests
package com.kd.mybatisplus;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kd.mybatisplus.entity.Product;
import com.kd.mybatisplus.mapper.ProductMapper;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@SpringBootTest
class MyBatisPlusApplicationTests {
    @Autowired
    private ProductMapper productMapper;

    /**
     * 插入操作
     */
    @Test
    void insert() {
        Product product = new Product();
        product.setTitle("小米");
        product.setPrice(2999L);
        product.setItemType("旗舰店");
        int row = productMapper.insert(product);

        log.info("Product--新增数据", row);
    }

    /**
     * 删除操作
     */
    @Test
    void deleteById() {
        int row = productMapper.deleteById(1700704257);

        log.info("Product--删除数据", row);
    }

    @Test
    void deleteBatchIds() {
        ArrayList<Integer> idList = new ArrayList<>();
        idList.add(1700704257);
        idList.add(228503554);
        //ArrayList<Integer> idList = new ArrayList<Integer>() {{
        //    add(1700704257);
        //    add(228503554);
        //}};
        int row = productMapper.deleteBatchIds(idList);

        log.info("Product--批量删除数据", row);
    }

    @Test
    void deleteByMap() {
        Map<String, Object> colunm = new HashMap<>();
        colunm.put("title", "小米");
        colunm.put("price", 2999L);
        int row = productMapper.deleteByMap(colunm);

        log.info("Product--对象删除数据", row);
    }

    @Test
    void delete() {
        UpdateWrapper<Product> wrapper = new UpdateWrapper<>();
        //gt:():大于,where price >2000 OR id=10,name like "%小米%"
        wrapper.gt("price", 2000).or().likeRight("title", "小米");
        int row = productMapper.delete(wrapper);

        log.info("Product--条件构造器:删除数据", row);
    }

    /**
     * 更新数据
     */
    @Test
    void updateById() {
        Product product = new Product();
        product.setId(10000001);
        product.setTitle("小米");
        int row = productMapper.updateById(product);

        log.info("Product--根据Id更新数据", row);
    }

    @Test
    void update() {
        Product product = new Product();
        product.setId(10000001);

        UpdateWrapper<Product> wrapper = new UpdateWrapper<>();
        wrapper.gt("price", 80).set("title", "小米").set("price", "3999").set(false, "num", null);

        int row = productMapper.update(product, wrapper);

        log.info("Product--更新数据", row);
    }

    /**
     * 查询数据
     */
    @Test
    void selectById() {
        Product product = productMapper.selectById(10000001);

        log.info("Product--根据ID查询", product);
        System.err.println(product);
    }

    @Test
    void selectBatchIds() {
        List<Integer> ids = new ArrayList<>();
        ids.add(10000001);
        ids.add(228503554);
        List<Product> products = productMapper.selectBatchIds(ids);

        log.info("Product--根据ID批量查询", products);
        //输出集合中所有元素的信息
        products.forEach(System.out::println);
    }

    @Test
    void selectByMap() {
        Map<String, Object> colunm = new HashMap<>();
        colunm.put("title", "小米");
        List<Product> products = productMapper.selectByMap(colunm);

        log.info("Product--根据columnMap条件", products);
        products.forEach(System.out::println);
    }

    @Test
    void selectList() {
        UpdateWrapper<Product> wrapper = new UpdateWrapper<>();
        wrapper.gt("price", 1999).eq("title", "小米");
        List<Product> products = productMapper.selectList(wrapper);

        log.info("Product--根据 entity 条件,查询全部记录", products);
        products.forEach(System.out::println);
    }

    /**
     * 分页查询
     */
    @Test
    void selectPage() {
        IPage<Product> page = new Page<>(1, 5);
        /*查询构造条件:QueryWrapper,增删改:UpdateWrapper*/
        QueryWrapper<Product> wrapper = new QueryWrapper<>();
        wrapper.eq("status", 1);

        IPage<Product> pageInfo = productMapper.selectPage(page, wrapper);
        List<Product> products = pageInfo.getRecords();

        products.forEach(System.out::println);
        log.info("Product--根据 entity 条件,查询全部记录(并翻页)", products);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Sun Peng

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值