Springboot整合mybatis+mybatis-plus+PageHelper

本文详细介绍了如何在Spring Boot应用中整合Mybatis 3.0后的@Mapper注解,包括配置POM、YAML、数据模型、Mapper接口编写、整合PageHelper以及自定义SQL。通过实例演示了如何简化XML配置,提升开发效率。

Mybatis是在国内使用是最广泛的,以前都是使用xml进行映射,说实话真心不太好用,维护起来也不太方便。 从mybatis3.0后开始支持 @Mapper注解,极大方便了开发,几乎不在需要任何xml进行配置了。下面重点就讲下Mybatis的相关整合与@Mapper的使用。

首先,配置pom.xml文件,添加以下配置项

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.4</version>
</dependency>
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.4.1</version>
</dependency>

第二步,在application.yml配置文件中添加以下配置项

spring:
  datasource:
    platform: mysql
    url: jdbc:mysql://localhost/jeealfa_boot?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&transformedBitIsBoolean=true&autoReconnect=true&failOverReadOnly=false
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver
    initialization-mode: never
    schema: classpath:db/schema.sql
# 配置slq打印日志
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    map-underscore-to-camel-case: true

schema.sql文件内容户名测试要用,可以收到创建数据库,然后运行,如下: 也可以把 initialization-mode值设为always, 首次运行后修改为never.

drop table IF exists `user`;
create table `user`(
  `id` int(11) not null auto_increment,
  `name` varchar(60) not null default "" comment "姓名",
  `age` int(11) not null default 0,
  primary key (`id`),
  unique key (`name`)
)engine=InnoDB default charset=utf8;

第三步,创建数据model,内容如下

package com.jeealfa.model;

import lombok.Data;

@Data
public class User {
    private int id;
    private String name;
    private int age;
}

第四步,创建UserMapper,内容如下

package com.jeealfa.mapper;

import com.jeealfa.model.User;
import org.apache.ibatis.annotations.*;

@Mapper
public interface UserMapper {
    @Select("SELECT * FROM user WHERE id = #{id}")
    User queryById(@Param("id") int id);

    @Insert("INSERT INTO user(name,age) VALUES(#{name},#{age})")
    int add(User user);

    @Delete("DELETE FROM user WHERE id = #{id}")
    int delById(int id);

    @Update("UPDATE user SET name=#{name},age=#{age} WHERE id=#{id}")
    int updateById(User user);
}

第五步,在Controller中使用

//省略
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @RequestMapping("/querybyid")
    public User queryById(int id){
        return userMapper.queryById(id);
    }

    @RequestMapping("/add")
    public String add(User user){
        return userMapper.add(user) == 1?"success":"failed";
    }
}

第六步,mybatis-plus提供了BaseMapper,提供了一些列通用功能,极大方便了Mapper的开发,使用中可以直接继承此接口。BaseMapper提供的功能有:

package com.baomidou.mybatisplus.core.mapper;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Param;

public interface BaseMapper<T> extends Mapper<T> {
    int insert(T entity);

    int deleteById(Serializable id);

    int deleteByMap(@Param("cm") Map<String, Object> columnMap);

    int delete(@Param("ew") Wrapper<T> queryWrapper);

    int deleteBatchIds(@Param("coll") Collection<? extends Serializable> idList);

    int updateById(@Param("et") T entity);

    int update(@Param("et") T entity, @Param("ew") Wrapper<T> updateWrapper);

    T selectById(Serializable id);

    List<T> selectBatchIds(@Param("coll") Collection<? extends Serializable> idList);

    List<T> selectByMap(@Param("cm") Map<String, Object> columnMap);

    T selectOne(@Param("ew") Wrapper<T> queryWrapper);

    Integer selectCount(@Param("ew") Wrapper<T> queryWrapper);

    List<T> selectList(@Param("ew") Wrapper<T> queryWrapper);

    List<Map<String, Object>> selectMaps(@Param("ew") Wrapper<T> queryWrapper);

    List<Object> selectObjs(@Param("ew") Wrapper<T> queryWrapper);

    <E extends IPage<T>> E selectPage(E page, @Param("ew") Wrapper<T> queryWrapper);

    <E extends IPage<Map<String, Object>>> E selectMapsPage(E page, @Param("ew") Wrapper<T> queryWrapper);
}

UserMapper可以改为

@Mapper
public interface UserMapper extends BaseMapper<User>{   
}

第7步,整合pageHelper, 在pom.xml里添加

<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper-spring-boot-starter</artifactId>
    <version>1.2.3</version>
</dependency>
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper-spring-boot-autoconfigure</artifactId>
    <version>1.2.3</version>
</dependency>

在application.yml里新增如下篇日志项:

pagehelper:
  helper-dialect: mysql
  reasonable: true
  support-methods-arguments: true
  params: count=countSql

第8步,在控制器中使用分页

@RequestMapping("/user/list")
public Page<User> getMap(@RequestParam(value = "page", defaultValue = "0") int page,
                         @RequestParam(value = "size", defaultValue = "5") int size){
    PageHelper.startPage(page, size, "id desc");
    Page<User> list = userMapper.listAll();
    System.out.println(list);
    return list;
}

注意:PageHelper.startPage执行之后,必须紧跟列表查询方法,不然分页可能会不起作用。

UserMapper中添加listAll接口方法,如下

package com.jeealfa.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.github.pagehelper.Page;
import com.jeealfa.model.User;
import org.apache.ibatis.annotations.*;

@Mapper
public interface UserMapper2 extends BaseMapper<User> {

    @Select("SELECT * FROM user")
    Page<User> listAll();

}

可通过postman进行测试。

第9步,自定义sql。 Mybatis提供了@SelectProvider注解来进行自定义sql查询。

见下面事例:

package com.jeealfa.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.github.pagehelper.Page;
import com.jeealfa.model.User;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.builder.annotation.ProviderContext;
import org.apache.ibatis.jdbc.SQL;

import java.util.List;
import java.util.Map;

@Mapper
public interface UserMapper extends BaseMapper<User> {

    @Select("SELECT * FROM user")
    Page<User> listAll();

    @SelectProvider(type = UserMapper.SelectSql.class, method = "sql")
    List<User> queryByPage(Page page, @Param("orderby") String orderby);
    
    class SelectSql{
        public String sql(Object object, ProviderContext context){
            Map map = (Map) object;
            Page page = (Page) map.get("page");
            String orderby = (String) map.get("orderby");

            return (new SQL()).SELECT("*").FROM("user").
                    ORDER_BY(orderby).
                    LIMIT(page.getStartRow()+","+page.getPageSize())
                    .toString();
        }
    }
}

自定义sql是灵活的,利用SelectProvider, 甚至可以自己手动写一个BaseMapper。

<think>好的,我现在需要帮助用户找到使用SpringBootMyBatis和Vue实现分页功能的示例代码和教程。用户可能正在开发一个需要分页功能的Web应用,希望了解前后端如何配合实现这一功能。首先,我应该回顾用户提供的引用内容,看看里面有没有相关的配置或代码示例。 引用1提到了pagehelper组件在SpringBoot中的使用,引用了配置文件和分页插件的设置。引用2和3都涉及到MyBatis Plus的分页配置,特别是引用3详细说明了如何配置MybatisPlusInterceptor并指定数据库类型。引用4则给出了SpringBoot的配置文件示例,包括数据源和MyBatis的相关设置。这些引用内容主要集中在后端配置上,但用户还提到了Vue,所以需要整合前端部分。 接下来,我需要构建一个分步的解决方案,涵盖后端和前端。后端部分应该包括SpringBoot整合MyBatis Plus的分页插件,创建控制器和服务层来处理分页请求。前端部分需要Vue组件发送分页请求并处理响应数据,展示分页导航。 首先,后端配置方面,根据引用3的内容,配置MybatisPlusInterceptor并添加分页插件,指定数据库类型为MySQL。然后在服务层使用Page对象进行查询,控制器返回分页结果。引用2中的@MapperScan注解也是关键,确保Mapper接口被正确扫描。 前端部分,用户可能需要使用Vue发送GET请求,传递当前页和每页大小的参数。使用axios进行HTTP通信,接收后端返回的分页数据,并在页面上展示列表和分页控件。引用4中的端口号和数据源配置也需要在后端配置文件中设置,确保前后端连接正确。 可能的问题包括分页插件的正确配置、前后端参数传递的一致性,以及Vue组件中处理分页事件的方法。需要确保后端返回的数据结构符合前端预期,比如包含记录列表、当前页、总页数等信息。此外,跨域问题也需要处理,可以在后端添加CORS配置。 最后,生成相关问题,帮助用户深入理解分页实现的各个方面,比如性能优化、异常处理、样式调整等。需要确保提供的代码示例正确,并符合用户的技术栈要求,比如MyBatis Plus和Vue的版本兼容性。</think>### SpringBoot+MyBatis+Vue分页实现方案 #### 一、后端实现(SpringBoot+MyBatis Plus) 1. **添加依赖** ```xml <!-- pom.xml --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.3</version> </dependency> ``` 2. **配置分页插件** ```java @Configuration public class MybatisPlusConfig { @Bean public MybatisPlusInterceptor mybatisPlusInterceptor() { MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); return interceptor; } } ``` 3. **Service层实现** ```java @Service public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService { public Page<User> getPage(int current, int size) { Page<User> page = new Page<>(current, size); return this.page(page); } } ``` 4. **Controller层接口** ```java @RestController @RequestMapping("/api/user") public class UserController { @Autowired private UserService userService; @GetMapping("/page") public Result<Page<User>> getPage(@RequestParam(defaultValue = "1") int current, @RequestParam(defaultValue = "10") int size) { return Result.success(userService.getPage(current, size)); } } ``` #### 二、前端实现(Vue3+Element Plus) 1. **分页组件** ```vue <template> <el-table :data="tableData"> <!-- 列定义 --> </el-table> <el-pagination v-model:current-page="currentPage" :page-size="pageSize" :total="total" @current-change="handlePageChange" /> </template> <script setup> import { ref, onMounted } from 'vue' import axios from 'axios' const currentPage = ref(1) const pageSize = ref(10) const total = ref(0) const tableData = ref([]) const loadData = async () => { const res = await axios.get('/api/user/page', { params: { current: currentPage.value, size: pageSize.value } }) tableData.value = res.data.records total.value = res.data.total } onMounted(loadData) const handlePageChange = (newPage) => { currentPage.value = newPage loadData() } </script> ``` #### 三、关键配置说明 1. **application.yml配置** ```yaml spring: datasource: url: jdbc:mysql://localhost:3306/dbname?useSSL=false&serverTimezone=UTC username: root password: root driver-class-name: com.mysql.cj.jdbc.Driver mybatis-plus: configuration: map-underscore-to-camel-case: true ``` 2. **跨域配置(后端)** ```java @Configuration public class CorsConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("*") .allowedMethods("GET", "POST"); } } ``` 该方案实现了以下功能特性: - 后端采用MyBatis Plus自动分页查询 - 前端使用Element Plus分页组件 - 支持动态页码切换 - 每页条数可配置化 - 自动处理分页参数映射
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值