Mybatis-Plus 的简单使用

时间:2022-07-26
本文章向大家介绍Mybatis-Plus 的简单使用,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1.1 简介

1.1.1 概述

  MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。在不用编写任何 SQL 语句的情况下即可以极其方便的实现单一、批量、分页等操作。MyBatis-Plus 的增强,其实就是在 MyBatis 的基础上进行了自己的封装和拓展,可以让使用者不写 xml 文件,只需简单配置,即可快速进行 CRUD 操作,从而节省大量时间,简化了开发。

1.1.2 相关依赖

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus</artifactId>
    <version>3.4.0</version>
</dependency>

1.2 简单使用

1.2.1 配置

☞ Mybatis 的配置

<!-- 配置 sessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource"></property>
    <!-- 加载 mybatis 核心文件-->
    <property name="configLocation" value="classpath:mybatis.xml"></property>
</bean>

<!-- 扫描 mapper 所在的包 为 mapper 创建实现类-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="com.software.ssm.mapper"></property>
</bean>

☞ Mybatis-Plus 的配置

<!-- 使用 MP 提供的 sessionFactory,完成 Spring 与 MP 的整合 -->
<bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource"></property>
    <!-- 加载 mybatis 核心文件-->
    <property name="configLocation" value="classpath:mybatis.xml"></property>
</bean>

<!-- 扫描 mapper 所在的包 为 mapper 创建实现类-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="com.software.ssm.mapper"></property>
</bean>

1.2.2 常用注解

注解

说明

@TableName

描述:表名注解属性:value ☞ 表名   schema ☞ schema   keepGlobalPrefix ☞ 是否保持使用全局的 tablePrefix 的值,默认值 false(如果设置了全局 tablePrefix 且自行设置了 value 的值)   resultMap ☞ xml 中 resultMap 的 id   autoResultMap ☞ 是否自动构建 resultMap 并使用,默认值 false(如果设置 resultMap 则不会进行 resultMap 的自动构建并注入)

@TableId

描述:主键注解属性:value ☞ 主键字段名   type ☞ 主键类型,默认值 IdType.NONE    AUTO:数据库ID自增    NONE:无状态,该类型为未设置主键类型(注解里等于跟随全局,全局里约等于 INPUT)    INPUT:insert 前自行 set 主键值    ASSIGN_ID:分配ID(主键类型为 Number 或 String,使用接口 IdentifierGenerator 的方法 nextId (默认雪花算法)    ASSIGN_UUID:分配 UUID,主键类型为 String,使用接口 IdentifierGenerator 的方法 nextUUID(默认 default 方法)

@TableField

描述:字段注解(非主键)属性:value ☞ 数据库字段名   el ☞ 映射为原生 #{ … } 逻辑,相当于写在 xml 里的 #{ … } 部分   exist ☞ 是否为数据库表字段,默认 true   condition ☞ 字段 where 实体查询比较条件,有值设置则按设置的值为准,没有则为默认全局的 %s=#{%s}   update ☞ 字段 update set 部分注入, 例如:update="%s+1" 表示更新时会 set version=version+1(该属性优先级高于 el 属性)   select ☞ 是否进行 select 查询,默认 true   keepGlobalFormat ☞ 是否保持使用全局的 format 进行处理,默认 false   jdbcType ☞ JDBC 类型,默认 JdbcType.UNDEFINED (该默认值不代表会按照该值生效)   typeHandler ☞ 类型处理器,默认 UnknownTypeHandler.class (该默认值不代表会按照该值生效)   numericScale ☞ 指定小数点后保留的位数

1.2.3 实体类

/**
 * Created with IntelliJ IDEA.
 *
 * @author Demo_Null
 * @date 2020/9/11
 * @description 实体类
 */
@Data // Lombok 注解
public class Student {
	@TableId
    private Long id;
    private String name;
    private Integer age;
}

1.2.4 mapper

/**
 * Created with IntelliJ IDEA.
 *
 * @author Demo_Null
 * @date 2020/9/11
 * @description 数据访问层接口,继承 Mybatis-Plus 的 BaseMapper<T>
 */
@Repository
public interface StudentMapper extends BaseMapper<Student> {}

1.2.5 测试

/**
 * Created with IntelliJ IDEA.
 *
 * @author Demo_Null
 * @date 2020/9/11
 * @description 测试类
 */
@SpringJUnitConfig(locations = "classpath:application.xml")
public class Demo {

    @Autowired
    private StudentMapper studentMapper;

    @Test
    public void TestSelect() {
        List<Student> students = studentMapper.selectList(null);
        System.out.println(students);
    }
}

1.3 通用 CRUD

1.3.1 插入操作

☞ int insert(T entity)

/**
 * Created with IntelliJ IDEA.
 *
 * @author Demo_Null
 * @date 2020/9/11
 * @description 插入操作
 */
@SpringJUnitConfig(locations = "classpath:application.xml")
public class Demo {

    @Autowired
    private StudentMapper studentMapper;

    @Test
    public void TestInsert() {
        Student student = new Student();
        student.setName("大锤");
        student.setAge(800);

        studentMapper.insert(student);
        System.out.println(student);
    }
}

  咱们可以看到自动生成的主键是一个不知道是啥的数字,这个是应为我们没有设置主键增长类型,我们再实体类中使用 @TableId(type = IdType.AUTO) 设置为自动增长即可

1.3.2 更新操作

☞ int updateById(@Param(“et”) T entity)

/**
 * Created with IntelliJ IDEA.
 *
 * @author Demo_Null
 * @date 2020/9/11
 * @description 根据 id 修改
 */
@SpringJUnitConfig(locations = "classpath:application.xml")
public class Demo {

    @Autowired
    private StudentMapper studentMapper;

    @Test
    public void TestUpdate() {
        Student student = new Student();
        student.setId(1L);
        student.setName("姬发");

        int i = studentMapper.updateById(student);
        System.out.println("影响的行数:" + i);
    }
}

☞ int update(@Param(“et”) T entity, @Param(“ew”) Wrapper<T> updateWrapper)

/**
 * Created with IntelliJ IDEA.
 *
 * @author Demo_Null
 * @date 2020/9/11
 * @description 根据条件更新
 */
@SpringJUnitConfig(locations = "classpath:application.xml")
public class Demo {

    @Autowired
    private StudentMapper studentMapper;

    @Test
    public void TestUpdate() {
        Student student = new Student();
        student.setAge(900);

        QueryWrapper<Student> studentQueryWrapper = new QueryWrapper<Student>();
        studentQueryWrapper.eq("name", "姬发");

        int i = studentMapper.update(student, studentQueryWrapper);
        System.out.println("影响的行数:" + i);
    }
}

1.3.3 删除操作

☞ int deleteById(Serializable id)

/**
 * Created with IntelliJ IDEA.
 *
 * @author Demo_Null
 * @date 2020/9/11
 * @description 根据 id 删除
 */
@SpringJUnitConfig(locations = "classpath:application.xml")
public class Demo {

    @Autowired
    private StudentMapper studentMapper;

    @Test
    public void TestDel() {
        int i = studentMapper.deleteById(1L);
        System.out.println("影响的行数:" + i);
    }
}

☞ int deleteByMap(@Param(“cm”) Map<String, Object> columnMap)

/**
 * Created with IntelliJ IDEA.
 *
 * @author Demo_Null
 * @date 2020/9/11
 * @description 根据 Map 中的条件删除,为空则删除所有
 */
@SpringJUnitConfig(locations = "classpath:application.xml")
public class Demo {

    @Autowired
    private StudentMapper studentMapper;

    @Test
    public void TestDel() {
        Map<String, Object> columnMap = new HashMap<>();
        columnMap.put("name", "张良");
        columnMap.put("age", 200);

        int i = studentMapper.deleteByMap(columnMap);
        System.out.println("影响的行数:" + i);
    }
}

☞ int delete(@Param(“ew”) Wrapper<T> wrapper)

/**
 * Created with IntelliJ IDEA.
 *
 * @author Demo_Null
 * @date 2020/9/11
 * @description 根据条件删除
 */
@SpringJUnitConfig(locations = "classpath:application.xml")
public class Demo {

    @Autowired
    private StudentMapper studentMapper;

    @Test
    public void TestDel() {
        QueryWrapper<Student> studentQueryWrapper = new QueryWrapper<>();
        // 可以使用链式编程
        studentQueryWrapper.eq("age", 280);
        studentQueryWrapper.like("name", "李");

        int i = studentMapper.delete(studentQueryWrapper);
        System.out.println("影响的行数:" + i);
    }
}

☞ int deleteBatchIds(@Param(“coll”) Collection<? extends Serializable> idList)

/**
 * Created with IntelliJ IDEA.
 *
 * @author Demo_Null
 * @date 2020/9/11
 * @description 根据 id 批量删除
 */
@SpringJUnitConfig(locations = "classpath:application.xml")
public class Demo {

    @Autowired
    private StudentMapper studentMapper;

    @Test
    public void TestDel() {
        List<Long> list = new ArrayList<>();
        list.add(7L);
        list.add(8L);
        list.add(9L);

        int i = studentMapper.deleteBatchIds(list);
        System.out.println("影响的行数:" + i);
    }
}

1.3.4 查询操作

☞ T selectById(Serializable id)

/**
 * Created with IntelliJ IDEA.
 *
 * @author Demo_Null
 * @date 2020/9/11
 * @description 根据 id 查询
 */
@SpringJUnitConfig(locations = "classpath:application.xml")
public class Demo {

    @Autowired
    private StudentMapper studentMapper;

    @Test
    public void TestSelect() {
        Student student = studentMapper.selectById(10L);
        System.out.println(student);
    }
}

☞ List selectBatchIds(@Param(“coll”) Collection<? extends Serializable> idList)

/**
 * Created with IntelliJ IDEA.
 *
 * @author Demo_Null
 * @date 2020/9/11
 * @description 根据 id 批量查询,参数不能为空
 */
@SpringJUnitConfig(locations = "classpath:application.xml")
public class Demo {

    @Autowired
    private StudentMapper studentMapper;

    @Test
    public void TestSelect() {
        List<Long> list = new ArrayList<>();
        list.add(10L);
        list.add(11L);

        List<Student> students = studentMapper.selectBatchIds(list);
        System.out.println(students);
    }
}

☞ List selectByMap(@Param(“cm”) Map<String, Object> columnMap)

/**
 * Created with IntelliJ IDEA.
 *
 * @author Demo_Null
 * @date 2020/9/11
 * @description 根据 Map 查询
 */
@SpringJUnitConfig(locations = "classpath:application.xml")
public class Demo {

    @Autowired
    private StudentMapper studentMapper;

    @Test
    public void TestSelect() {
        HashMap<String, Object> columnMap = new HashMap<>();
        columnMap.put("name", "张良");

        List<Student> students = studentMapper.selectByMap(columnMap);
        System.out.println(students);
    }
}

☞ T selectOne(@Param(“ew”) Wrapper<T> queryWrapper)

/**
 * Created with IntelliJ IDEA.
 *
 * @author Demo_Null
 * @date 2020/9/11
 * @description 根据条件查询一条数据
 */
@SpringJUnitConfig(locations = "classpath:application.xml")
public class Demo {

    @Autowired
    private StudentMapper studentMapper;

    @Test
    public void TestSelect() {
        QueryWrapper<Student> studentQueryWrapper = new QueryWrapper<>();
        studentQueryWrapper.eq("id", 10L);

        Student student = studentMapper.selectOne(studentQueryWrapper);
        System.out.println(student);
    }
}

☞ List selectList(@Param(“ew”) Wrapper<T> queryWrapper)

/**
 * Created with IntelliJ IDEA.
 *
 * @author Demo_Null
 * @date 2020/9/11
 * @description 根据条件查询
 */
@SpringJUnitConfig(locations = "classpath:application.xml")
public class Demo {

    @Autowired
    private StudentMapper studentMapper;

    @Test
    public void TestSelect() {
        QueryWrapper<Student> studentQueryWrapper = new QueryWrapper<>();
        studentQueryWrapper.like("name", "左");

        List<Student> students = studentMapper.selectList(studentQueryWrapper);
        System.out.println(students);
    }
}

☞ Integer selectCount(@Param(“ew”) Wrapper<T> queryWrapper)

/**
 * Created with IntelliJ IDEA.
 *
 * @author Demo_Null
 * @date 2020/9/11
 * @description 统计符合条件的数据
 */
@SpringJUnitConfig(locations = "classpath:application.xml")
public class Demo {

    @Autowired
    private StudentMapper studentMapper;

    @Test
    public void TestSelect() {
        QueryWrapper<Student> studentQueryWrapper = new QueryWrapper<>();
        studentQueryWrapper.like("name", "左");

        Integer integer = studentMapper.selectCount(studentQueryWrapper);
        System.out.println("有 " + integer + " 条数据");
    }
}

1.3.5 分页

☞ 配置

<!-- 配置 sessionFactory -->
<bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource"></property>
    <!-- 加载 mybatis 核心文件-->
    <property name="configLocation" value="classpath:mybatis.xml"></property>
    <!-- 分页 -->
    <property name="plugins">
        <array>
            <bean class="com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor">
            </bean>
        </array>
    </property>
</bean>

☞ 示例

/**
 * Created with IntelliJ IDEA.
 *
 * @author Demo_Null
 * @date 2020/9/11
 * @description 分页查询
 */
@SpringJUnitConfig(locations = "classpath:application.xml")
public class Demo {

    @Autowired
    private StudentMapper studentMapper;

    @Test
    public void TestPage() {
        QueryWrapper<Student> studentQueryWrapper = new QueryWrapper<>();

        Page<Student> page = new Page<>();
        page.setSize(2);
        page.setCurrent(1);

        IPage<Student> selectPage = studentMapper.selectPage(page, studentQueryWrapper);
        System.out.println("总条数" + selectPage.getTotal());
        System.out.println("总页数" + selectPage.getPages());
        System.out.println("每页显示" + selectPage.getSize());
        System.out.println("当前页" + selectPage.getCurrent());
        System.out.println(selectPage.getRecords());
    }
}