Mybatis-plus使用分页插件(版本是 3.0.7.1)

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_36984017/article/details/86665467

一:(建项目<web+mybatis+jdbc+mysql>)再干掉mybatis的包,因为mybatis-plus已经集成了mybatis,最终的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 http://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.1.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>mybatis</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        
        <!--这就是mybatis-plus的包-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.0.7.1</version>
        </dependency>
        <!--这就是mybatis-plus的包-->

        <!--mysql的连接器-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!--mysql的连接器-->

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

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.2</version>
                <configuration>
                    <configurationFile>GeneratorMapper.xml</configurationFile>
                    <verbose>true</verbose>
                    <overwrite>true</overwrite>
                </configuration>
            </plugin>
        </plugins>

        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.*</include>
                </includes>
            </resource>
            <!--<resource>-->
                <!--<directory>src/main/webapp</directory>-->
                <!--<targetPath>META-INF/resources</targetPath>-->
                <!--<includes>-->
                    <!--<include>**/*.*</include>-->
                <!--</includes>-->
            <!--</resource>-->
        </resources>

    </build>
</project>

二:生成model(表映射实体类)

package com.mybatis.model;

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 java.io.Serializable;

//指定该model映射为com表
@TableName(value = "com")
public class ComTable implements Serializable {
    //    @TableId(value="id",type= IdType.AUTO) 已经在全局配置了主键策略,所以没必要了
    private Byte id;

    private String content;

    private Integer comId;

    //表示数据库中没有这个字段,自动过滤掉这个字段
    @TableField(exist = false)
    private User user;

    public User getUser() {
        return user;
    }

    private static final long serialVersionUID = 1L;

    public ComTable(String content, Integer comId) {
        this.content = content;
        this.comId = comId;
    }

    public ComTable(Byte id, String content, Integer comId) {
        this.id = id;
        this.content = content;
        this.comId = comId;
    }

    public ComTable() {
    }

    public Byte getId() {
        return id;
    }

    public void setId(Byte id) {
        this.id = id;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content == null ? null : content.trim();
    }

    public Integer getComId() {
        return comId;
    }

    public void setComId(Integer comId) {
        this.comId = comId;
    }

    @Override
    public String toString() {
        return "ComTable{" +
                "id=" + id +
                ", content='" + content + '\'' +
                ", comId=" + comId +
                '}';
    }
}

三:建mapper

package com.mybatis.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.mybatis.model.ComTable;
import org.springframework.stereotype.Repository;

@Repository
//mybatis-plus的mapper就需要去继承BaseMapper并传入映射的实体类,mybatis的mapper就不需要继承这个类
public interface ComTableMapper extends BaseMapper<ComTable> {

}

四:建mapper.xml来去承接mapper接口的实现并操作数据库(注:在本项目中主要是讲mybatis-plus,所以这步不是必须的,所以可以看见在xml中有许多的方法在mapper接口中并没有定义)

<?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.mybatis.mapper.ComTableMapper">
    <resultMap id="BaseResultMap" type="com.mybatis.model.ComTable">
        <id column="id" property="id" jdbcType="TINYINT"/>
        <result column="content" property="content" jdbcType="VARCHAR"/>
        <result column="com_id" property="comId" jdbcType="INTEGER"/>
    </resultMap>
    <sql id="Base_Column_List">
    id, content, com_id
  </sql>
    <select id="selectByPrimaryKey" resultMap="BaseResultMap">
        select
        <include refid="Base_Column_List"/>
        from com
        where id = #{id,jdbcType=TINYINT}
    </select>

    <select id="selectDai" resultType="com.mybatis.model.ComTable">
    select * from com where id=#{list[2]}
  </select>

    <select id="map" resultType="com.mybatis.model.ComTable">
    select * from com where content="sdfasdfa"
  </select>

    <resultMap id="selectUser1" type="com.mybatis.model.ComTable">
        <id column="id" property="id"/>
        <result column="content" property="content"/>
        <association property="user" javaType="com.mybatis.model.User">
            <id column="uid" property="id"/>
            <result column="name" property="name"/>
            <result column="age" property="age"/>
        </association>
    </resultMap>

    <resultMap id="selectUser2" type="com.mybatis.model.ComTable">
        <id column="id" property="id"/>
        <result column="content" property="content"/>
        <result column="uid" property="user.id"/>
        <result column="name" property="user.name"/>
    </resultMap>

    <resultMap id="selectUser3" type="com.mybatis.model.ComTable">
        <id column="id" property="id"/>
        <result column="content" property="content"/>
        <association property="user"
                     select="com.mybatis.mapper.UserMapper.selectByPrimaryKey"
                     column="id"
        ></association>
    </resultMap>

    <select id="getCom" resultType="com.mybatis.model.ComTable">
  select * from com where com_id=#{comId}
</select>

    <select id="selectWh" resultType="com.mybatis.model.ComTable">
        select * from com
        <where>
            <if test="id!=null and id!=''">id=#{id}</if>
            <if test="content!=null and content.trim()!=''">and content like #{content}</if>
            <if test="comId!=null">and com_id=#{comId}</if>
        </where>
    </select>
    <insert id="insertMo">
        insert into com(content,com_id) values
        <foreach collection="list" item="val" separator=",">
            (#{val.content},#{val.comId})
        </foreach>
    </insert>
    <select id="selectIn" resultType="com.mybatis.model.ComTable">
        select * from com where id in
        <foreach collection="a" item="val" open="(" close=")" separator=",">
            #{val}
        </foreach>
        and content like #{content}
    </select>
    <select id="selectUser" resultMap="selectUser3">
    select * from com where id=#{id}
  </select>
    <delete id="deleteByPrimaryKey" parameterType="java.lang.Byte">
    delete from com
    where id = #{id,jdbcType=TINYINT}
  </delete>
    <!--<insert id="insert"  useGeneratedKeys="true" keyProperty="id">-->
    <!--insert into com (id, content, com_id-->
    <!--)-->
    <!--values (#{id,jdbcType=TINYINT}, #{content,jdbcType=VARCHAR}, #{comId,jdbcType=INTEGER}-->
    <!--)-->
    <!--</insert>-->
    <insert id="insertSelective" parameterType="com.mybatis.model.ComTable">
        insert into com
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="id != null">
                id,
            </if>
            <if test="content != null">
                content,
            </if>
            <if test="comId != null">
                com_id,
            </if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
            <if test="id != null">
                #{id,jdbcType=TINYINT},
            </if>
            <if test="content != null">
                #{content,jdbcType=VARCHAR},
            </if>
            <if test="comId != null">
                #{comId,jdbcType=INTEGER},
            </if>
        </trim>
    </insert>
    <update id="updateByPrimaryKeySelective" parameterType="com.mybatis.model.ComTable">
        update com
        <set>
            <if test="content != null">
                content = #{content,jdbcType=VARCHAR},
            </if>
            <if test="comId != null">
                com_id = #{comId,jdbcType=INTEGER},
            </if>
        </set>
        where id = #{id,jdbcType=TINYINT}
    </update>
    <update id="updateByPrimaryKey" parameterType="com.mybatis.model.ComTable">
    update com
    set content = #{content,jdbcType=VARCHAR},
      com_id = #{comId,jdbcType=INTEGER}
    where id = #{id,jdbcType=TINYINT}
  </update>
</mapper>

五:在启动类上加上全局扫描用于扫描mapper

@MapperScan("com.mybatis.mapper")

六:配置数据库等信息

#扫描所有的xml文件
#mybatis.mapper-locations=classpath:com.mybatis.mapper/*.xml
#开启数据库和接口之间的驼峰命名映射  true:开启映射
#mybatis.configuration.map-underscore-to-camel-case=true
spring.datasource.username=root
spring.datasource.password=daibin
#spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf8&useSSL=false
#开启sql的打印
logging.level.com.mybatis.mapper=debug

#配置mybatisPlus主键策略为自增
mybatis-plus.global-config.db-config.id-type=auto
#配置表前缀
#mybatis-plus.global-config.db-config.table-prefix=aa_

七:model、两个mapper(一个接口,一个xml)这些配也配了,设置也设置起了,接下来就来看看Controller层对于mybatis-plus的基本实现

package com.mybatis.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mybatis.mapper.ComTableMapper;
import com.mybatis.model.ComTable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class He {
    
    //注入最基本的mapper接口
    @Autowired
    ComTableMapper comTableMapper;

    @RequestMapping("/aa")
    public Object in() {
        //mybatis-plus的简单实现----用了条件构造器来更新批量数据,返回影响的条数
        ComTable com = new ComTable("123123", 100);
        return comTableMapper.update(com, new QueryWrapper<ComTable>().eq("com_id", 555));
//        IPage<ComTable> list = comTableMapper.selectPage(new Page<ComTable>(1, 3), null);
//        return list;
    }
}


八:那么整个mybatis-plus的基本操作就是这样,下面我们看看mybatis-plus的分页操作是怎样的?
1、建一个confi文件夹(用来装各种配置类)
2、在文件夹中建一个分页插件的配置类,用@Configuration来标注,那么springboot就可以进行扫描配置

package com.mybatis.confi;

import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@MapperScan("com.mybatis.mapper.*")
public class PageConfi {
        @Bean
        public PaginationInterceptor paginationInterceptor() {
            // 这里就是分页插件的配置了,由于由@Configuration注解,所以是自动注入的,自动应用
            PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
            return paginationInterceptor;
        }
}

3、再回过头去看看控制器中是怎么进行分页的?

package com.mybatis.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mybatis.mapper.ComTableMapper;
import com.mybatis.model.ComTable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class He {

    //注入最基本的mapper接口
    @Autowired
    ComTableMapper comTableMapper;

    @RequestMapping("/aa")
    public Object in() {
        //mybatis-plus的简单实现----用了条件构造器来更新批量数据,返回影响的条数
//        ComTable com = new ComTable("123123", 100);
//        return comTableMapper.update(com, new QueryWrapper<ComTable>().eq("com_id", 555));
        
        //返回的是一个分页对象,一定要把各种泛型需要的实体类传进去
        IPage<ComTable> list = comTableMapper.selectPage(new Page<ComTable>(1, 3), null);
        return list;
    }
}

4、就这样简单的配置,简单的使用,就完成了分页,下面我们再看看数据是怎样的?(一眼就看出了很棒,前端需要的信息都有),就这样,mybatis-plus的基本使用和分页的插件的使用我们都over了,祝我越来越棒,2021年过上自己想要的生活

{
    "records":[
        {
            "id":32,
            "content":"嘿嘿哈",
            "comId":8,
            "user":null
        },
        {
            "id":33,
            "content":"角度思考计分卡了",
            "comId":9,
            "user":null
        },
        {
            "id":34,
            "content":"嘿嘿",
            "comId":10,
            "user":null
        }
    ],
    "total":39,
    "size":3,
    "current":1,
    "searchCount":true,
    "pages":13
}

猜你喜欢

转载自blog.csdn.net/qq_36984017/article/details/86665467