MybatisPlus简单的CRUD操作

1 MybatisPlus优点

  • 无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑
  • 损耗小:启动即会自动注入基本CURD,性能基本无损耗,直接面向对象操作
  • 强大的 CRUD 操作:内置通用 Mapper、通用Service,仅仅通过少量配置即可实现单表大部分 CRUD 操作,更有强大的条件构造器,满足各类使用需求
  • 支持 Lambda形式调用:通过 Lambda 表达式,方便的编写各类查询条件,无需再担心字段写错
  • 支持主键自动生成:支持多达 4种主键策略(内含分布式唯一 ID 生成器 - Sequence),可自由配置,完美解决主键问题
  • 支持 ActiveRecord 模式:支持ActiveRecord 形式调用,实体类只需继承 Model 类即可进行强大的 CRUD 操作
  • 支持自定义全局通用操作:支持全局通用方法注入( Write once, use anywhere )
  • 内置代码生成器:采用代码或者 Maven 插件可快速生成 Mapper 、 Model 、 Service 、 Controller层代码,支持模板引擎,更有超多自定义配置等您来使用
  • 内置分页插件:基于 MyBatis物理分页,开发者无需关心具体操作,配置好插件之后,写分页等同于普通 List 查询
  • 分页插件支持多种数据库:支持 MySQL、MariaDB、Oracle、DB2、H2、HSQL、SQLite、Postgre、SQLServer 等多种数据库
  • 内置性能分析插件:可输出 Sql 语句以及其执行时间,建议开发测试时启用该功能,能快速揪出慢查询
  • 内置全局拦截插件:提供全表 delete、 update 操作智能分析阻断,也可自定义拦截规则,预防误操作

2 maven依赖

<dependencies>
    <!-- mybatisPlus -->
    <dependency>
      <groupId>com.baomidou</groupId>
      <artifactId>mybatis-plus</artifactId>
      <version>2.3</version>
    </dependency>
    <!-- junit -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
    </dependency>
    <!-- c3p0 -->
    <dependency>
      <groupId>com.mchange</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.5.2</version>
    </dependency>
    <!-- mysql -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.37</version>
    </dependency>
    <!-- spring -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.2.5.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
      <version>5.2.5.RELEASE</version>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.6.1</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
    </plugins>
  </build>

3 Spring配置文件和Mybatis配置文件

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

  <!-- 数据源 -->
  <context:property-placeholder location="classpath:db.properties"/>
  <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <property name="driverClass" value="${jdbc.driver}"></property>
    <property name="jdbcUrl" value="${jdbc.url}"></property>
    <property name="user" value="${jdbc.username}"></property>
    <property name="password" value="${jdbc.password}"></property>
  </bean>

  <!-- 事务管理器 -->
  <bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"></property>
  </bean>
  <!-- 基于注解的事务管理 -->
  <tx:annotation-driven transaction-manager="dataSourceTransactionManager"/>

  <!-- SqlSessionFactory-->
  <bean id="sqlSessionFactoryBean" class="com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean">
    <!-- 数据源 -->
    <property name="dataSource" ref="dataSource"></property>
    <!-- 配置文件 -->
    <property name="configLocation" value="classpath:mybatis-config.xml"></property>
    <!-- 别名处理 -->
    <property name="typeAliasesPackage" value="com.lrm.bean"></property>
    <!-- 注入全局MP策略配置 -->
    <property name="globalConfig" ref="globalConfiguration"></property>
  </bean>

  <!-- 定义MybatisPlus的全局策略配置-->
  <bean id="globalConfiguration" class="com.baomidou.mybatisplus.entity.GlobalConfiguration">
    <!-- 在2.3版本以后,dbColumnUnderline 默认值就是true -->
    <property name="dbColumnUnderline" value="true"></property>
    <!-- 全局的主键策略 -->
    <property name="idType" value="0"></property>
    <!-- 全局的表前缀策略配置 -->
    <property name="tablePrefix" value="mp_"></property>
  </bean>

  <!-- 配置mybatis 扫描mapper接口的路径-->
  <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="com.lrm.mapper"></property>
  </bean>
</beans>

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
  <settings>
    <setting name="logImpl" value="STDOUT_LOGGING" />
  </settings>
</configuration>

4 BaseMapper

在这里插入图片描述
将EmployeeMapper继承BaseMapper接口,就可以得到BaseMapper已经定义好的十多种基本的CRUD操作。

package com.lrm.mapper;

import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.lrm.bean.Employee;

/**
 * @author RuiMing Lin
 * @date 2021-03-29 10:03
 * @description
 */
public interface EmployeeMapper extends BaseMapper<Employee> {
    
    

    
}

5 测试CRUD

package com.lrm.test;

import com.baomidou.mybatisplus.plugins.Page;
import com.lrm.bean.Employee;
import com.lrm.mapper.EmployeeMapper;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author RuiMing Lin
 * @date 2021-03-29 9:48
 * @description
 */
public class TestMP {
    
    

    private ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    private EmployeeMapper employeeMapper = context.getBean("employeeMapper", EmployeeMapper.class);


    @Test
    public void demo1() throws SQLException {
    
    
        // 测试数据库能否正常连接
        DataSource dataSource = context.getBean("dataSource", DataSource.class);
        System.out.println("dataSource = " + dataSource);
        Connection connection = dataSource.getConnection();
        System.out.println("connection = " + connection);
        connection.close();
    }

    @Test
    public void demo2() {
    
    
        // 新增数据:insert
        Employee employee = new Employee(null, "test_MP", "[email protected]", 1, 22);
        Integer result = employeeMapper.insert(employee);
        System.out.println("result = " + result);   // 成功插入的条数
        System.out.println("employee = " + employee);   // 测试主键是否回填
    }

    @Test
    public void demo3() {
    
    
        // 新增数据:insertAllColumn
        Employee employee = new Employee(null, "test_MP", null, null, 22);
        employeeMapper.insertAllColumn(employee);
        System.out.println("employee = " + employee);   // 测试主键是否回填
    }

    @Test
    public void demo4() {
    
    
        // 更新数据:updateById 发送的SQL语句会判断字段是否为空
        Employee employee = new Employee(15, "test_update", "[email protected]", 1, 22);
        Integer result = employeeMapper.updateById(employee);
        System.out.println("result = " + result);
    }

    @Test
    public void demo5() {
    
    
        // 更新数据:updateAllColumnById 发送的SQL语句更新所有列
        Employee employee = new Employee(15, "test_update", "[email protected]", 1, null);
        Integer result = employeeMapper.updateAllColumnById(employee);
        System.out.println("result = " + result);
    }

    @Test
    public void demo6() {
    
    
        // 删除数据:deleteById 根据传入的id删除数据
        Integer result = employeeMapper.deleteById(14);
        System.out.println("result = " + result);
    }

    @Test
    public void demo7() {
    
    
        // 删除数据:deleteByMap 根据传入的map删除数据
        HashMap<String, Object> map = new HashMap<>();
        map.put("last_name", "test_MP");
        map.put("gender", 1);
        Integer result = employeeMapper.deleteByMap(map);
        System.out.println("result = " + result);
    }

    @Test
    public void demo8() {
    
    
        // 查询数据:selectBatchIds  根据传入id集合查询
        ArrayList<Integer> idList = new ArrayList<>();
        idList.add(7);
        idList.add(8);
        idList.add(9);
        idList.add(10);
        Integer results = employeeMapper.deleteBatchIds(idList);
        System.out.println("results = " + results);
    }

    @Test
    public void demo9() {
    
    
        // 查询数据:selectById 通过id查询
        Employee employee = employeeMapper.selectById(15);
        System.out.println("employee = " + employee);
    }

    @Test
    public void demo10() {
    
    
        // 查询数据:selectOne 结果集只能包含一条  不然会报错
        Employee conditions = new Employee(8, "test_MP", null, 1, null);
        Employee employee = employeeMapper.selectOne(conditions);
        System.out.println("employee = " + employee);
    }

    @Test
    public void demo11() {
    
    
        // 查询数据:selectBatchIds  根据传入id集合查询
        ArrayList<Integer> idList = new ArrayList<>();
        idList.add(7);
        idList.add(8);
        idList.add(9);
        idList.add(10);
        List<Employee> employees = employeeMapper.selectBatchIds(idList);
        employees.forEach((employee) -> System.out.println("employee = " + employee));
    }

    @Test
    public void demo12() {
    
    
        // 查询数据:selectByMap  根据传入的map查询,map的key必须是数据表的列名
        HashMap<String, Object> map = new HashMap<>();
        map.put("last_name", "test_MP");
        map.put("gender", 1);
        List<Employee> employees = employeeMapper.selectByMap(map);
        employees.forEach((employee) -> System.out.println("employee = " + employee));
    }

    @Test
    public void demo13() {
    
    
        // 查询数据:selectPage 分页查询  不推荐,并不是使用物理分页,浪费内存资源
        List<Employee> employees = employeeMapper.selectPage(new Page<>(2, 2), null);
        employees.forEach((employee) -> System.out.println("employee = " + employee));
    }
}

猜你喜欢

转载自blog.csdn.net/Orange_minger/article/details/115325439