Mybatis Plus入门

01/22 22:41
阅读数 172

MyBatis Plus介绍

MyBatis Plus (简称MP)是国内人员开发的 MyBatis 增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。

特征

无侵入:Mybatis-Plus 在 Mybatis 的基础上进行扩展,只做增强不做改变,引入 Mybatis-Plus 不会对您现有的 Mybatis 构架产生任何影响,而且 MP 支持所有 Mybatis 原生的特性
依赖少:仅仅依赖 Mybatis 以及 Mybatis-Spring
损耗小:启动即会自动注入基本CURD,性能基本无损耗,直接面向对象操作
预防Sql注入:内置Sql注入剥离器,有效预防Sql注入攻击
通用CRUD操作:内置通用 Mapper、通用 Service,仅仅通过少量配置即可实现单表大部分 CRUD 操作,更有强大的条件构造器,满足各类使用需求
多种主键策略:支持多达4种主键策略(内含分布式唯一ID生成器),可自由配置,完美解决主键问题

框架结构

Mybatis Plus使用

1.导入依赖

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

2.MP整合的配置

<!-- 0.连接池属性设置读取指定的properties文件 -->
    <context:property-placeholder location="classpath:db.properties" ignore-unresolvable="true"/>
    
    <!-- 1.将连接池放入spring容器 -->
    <bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="jdbcUrl" value="${jdbc.url}"></property>
        <property name="driverClass" value="${jdbc.driver}"></property>
        <property name="user" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>

    <bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!-- 配置实体扫描路径,多个package可以用分号; 逗号, 分隔, 支持通配符*-->
        <!-- com.a.b.entity;com.a.c.entity;com.d.*.entity-->
        <property name="typeAliasesPackage" value="cn.xm.jwxt.bean.*"/>
        <property name="configuration" ref="mybatisConfig"/>
        <!-- MP 全局配置注入 -->
        <property name="globalConfig" ref="globalConfig"/>
        <property name="plugins">
            <array>
                <!-- 分页插件配置 -->
                <bean id="paginationInterceptor"
                      class="com.baomidou.mybatisplus.plugins.PaginationInterceptor"/>
                <!-- 性能拦截器,兼打印sql,不建议生产环境配置-->
                <bean id="performanceInterceptor"
                      class="com.baomidou.mybatisplus.plugins.PerformanceInterceptor"/>
            </array>
        </property>
    </bean>

    <bean id="mybatisConfig" class="com.baomidou.mybatisplus.MybatisConfiguration">
        <property name="mapUnderscoreToCamelCase" value="true"/>
    </bean>

    <!-- 定义 MP 全局策略 -->
    <bean id="globalConfig" class="com.baomidou.mybatisplus.entity.GlobalConfiguration">
       
        <property name="idType" value="2"/>

        <property name="dbType" value="mysql"/>

        <!-- 全局表为下划线命名设置 true -->
        <property name="dbColumnUnderline" value="true"/>
    </bean>

    <!-- 配置mybatis 扫描mapper接口的路径, 相当于注解@MapperScan,@MapperScan("com.baomidou.mybatisplus.test.h2.entity.mapper")-->
    <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="cn.xm.jwxt.mapper"/>
    </bean>

3.实体

@TableName(value="employee")
public
class Employee { private Integer id ; private String lastName; private String email ; private Integer gender; private Integer age ; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Integer getGender() { return gender; } public void setGender(Integer gender) { this.gender = gender; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { return "Employee [id=" + id + ", lastName=" + lastName + ", email=" + email + ", gender=" + gender + ", age=" + age + "]"; } }

4.mapper 接口

public interface EmployeeMapper extends BaseMapper<Employee> {}

5.新增

@Test
public void testCommonInsert() {
    //初始化Employee对象
    Employee employee  = new Employee();
    employee.setLastName("MP");
    employee.setEmail("mp@atguigu.com");
    employee.setGender(1);
    //insert方法在插入时,会根据实体类的每个属性进行非空判断,只有非空的属性对应的字段才会出现到SQL语句中
    Integer result = employeeMapper.insert(employee);
    System.out.println("result: " + result );
    //insertAllColumn方法在插入时,不管属性是否非空, 属性所对应的字段都会出现到SQL语句中.
    Integer result1 = employeeMapper.insertAllColumn(employee);
    System.out.println("result: " + result1 );
    //获取当前数据在数据库中的主键值
    Integer key = employee.getId();
    System.out.println("key:" + key );
}

6.修改

@Test
public void testCommonUpdate() {
    //初始化修改对象
    Employee employee = new Employee();
    employee.setId(7);
    employee.setLastName("王五");
    employee.setEmail("xz@sina.com");
    employee.setGender(0);
    //updateById方法在修改时,会根据实体类的每个属性进行非空判断,只有非空的属性对应的字段才会出现到SQL语句中
    Integer result = employeeMapper.updateById(employee);
    System.out.println("result: " + result );
    //updateAllColumnById方法在修改时,不管属性是否非空, 属性所对应的字段都会出现到SQL语句中.
    Integer result1 = employeeMapper.updateAllColumnById(employee);
    System.out.println("result: " + result1 );
}

7.查询

@Test
public void  testCommonSelect() {
    //1. 通过id查询
    Employee employee = employeeMapper.selectById(7);
    System.out.println(employee);

    //2. 通过多个列进行查询。selectOne查询结果只能是一条,否则报错
    Employee  employee1 = new Employee();
    employee.setLastName("王五");
    employee.setGender(0);
    Employee result = employeeMapper.selectOne(employee1);
    System.out.println("result: " +result );

    //3. 通过多个id进行查询
    List<Integer> idList = new ArrayList<>();
    idList.add(4);
    idList.add(5);
    idList.add(6);
    idList.add(7);
    List<Employee> emps = employeeMapper.selectBatchIds(idList);
    System.out.println(emps);

    //4. 通过Map封装条件查询。map中的key是数据库中字段名
    Map<String,Object> columnMap = new HashMap<>();
    columnMap.put("last_name", "Tom");
    columnMap.put("gender", 1);
    List<Employee> emps1 = employeeMapper.selectByMap(columnMap);
    System.out.println(emps1);

    //5. 分页查询
    List<Employee> emps2 = employeeMapper.selectPage(new Page<>(3, 2), null);
    System.out.println(emps2);
}

8.删除

@Test
public void testCommonDelete() {
    //1 .根据id进行删除
    Integer result = employeeMapper.deleteById(13);
    System.out.println("result: " + result );

    //2. 根据条件进行删除
    Map<String,Object> columnMap = new HashMap<>();
    columnMap.put("last_name", "MP");
    columnMap.put("email", "mp@atguigu.com");
    Integer result1 = employeeMapper.deleteByMap(columnMap);
    System.out.println("result: " + result1 );

    //3. 批量删除
    List<Integer> idList = new ArrayList<>();
    idList.add(3);
    idList.add(4);
    idList.add(5);
    Integer result2 = employeeMapper.deleteBatchIds(idList);
    System.out.println("result: " + result2 );
}

原文出处:https://www.cnblogs.com/dzlj/p/12229888.html

展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部