首页
/ MyBatis-Plus 开源项目教程

MyBatis-Plus 开源项目教程

2024-08-30 12:42:24作者:江焘钦

1、项目介绍

MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。MyBatis-Plus 提供了丰富的功能,如代码生成、自动分页、性能分析插件、SQL 注入器等,极大地简化了 MyBatis 的使用。

2、项目快速启动

环境准备

  • JDK 1.8 或更高版本
  • Maven 3.5.0 或更高版本
  • MySQL 5.7 或更高版本

引入依赖

在 Maven 项目的 pom.xml 文件中添加 MyBatis-Plus 依赖:

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.5.7</version>
</dependency>

配置数据源

application.yml 文件中配置数据源:

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/mybatis_plus?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai
    username: root
    password: 123456

创建实体类

创建一个简单的实体类 User.java

package com.example.entity;

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

@Data
@TableName("user")
public class User {
    private Long id;
    private String name;
    private Integer age;
    private String email;
}

创建 Mapper 接口

创建一个 Mapper 接口 UserMapper.java

package com.example.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.entity.User;

public interface UserMapper extends BaseMapper<User> {
}

配置扫描 Mapper

在 Spring Boot 启动类上添加 @MapperScan 注解:

package com.example;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.example.mapper")
public class MybatisPlusApplication {
    public static void main(String[] args) {
        SpringApplication.run(MybatisPlusApplication.class, args);
    }
}

测试

创建一个测试类 UserMapperTest.java

package com.example;

import com.example.entity.User;
import com.example.mapper.UserMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.List;

@SpringBootTest
public class UserMapperTest {
    @Autowired
    private UserMapper userMapper;

    @Test
    public void testSelect() {
        List<User> userList = userMapper.selectList(null);
        userList.forEach(System.out::println);
    }
}

3、应用案例和最佳实践

案例一:分页查询

MyBatis-Plus 提供了强大的分页插件,可以轻松实现分页查询。

package com.example.service;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.entity.User;
import com.example.mapper.UserMapper;
import org.springframework.stereotype.Service;

@Service
public class UserService extends ServiceImpl<UserMapper, User> {
    public Page<User> selectUserPage(Page<User> page)
登录后查看全文
热门项目推荐