MyBatis基础应用(四)——一篇文章教你学会MyBatis Plus

目录

1、MyBatis Plus简介

2、快速入门

3、Mapper CRUD 接口

Insert

Delete

Update

Select


1、MyBatis Plus简介

MyBatis-Plus(简称 MP),是一个 MyBatis 的增强工具包,只做增强不做改变. 发工作、提高生产率而生。MyBatis Plus 是国内团队(包米豆) 团队开发开源的!

官方地址:http://mp.baomidou.com

2、快速入门

1、创建数据库

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for tb_employee
-- ----------------------------
DROP TABLE IF EXISTS `tb_employee`;
CREATE TABLE `tb_employee`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `last_name` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL,
  `email` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL,
  `gender` char(1) CHARACTER SET utf8 COLLATE utf8_bin NULL DEFAULT NULL,
  `age` int(11) NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 9 CHARACTER SET = utf8 COLLATE = utf8_bin ROW_FORMAT = DYNAMIC;

-- ----------------------------
-- Records of tb_employee
-- ----------------------------
INSERT INTO `tb_employee` VALUES (1, '小AA', '234234@qq.com', '1', 18);
INSERT INTO `tb_employee` VALUES (2, 'White', 'white@163.com', '0', 35);
INSERT INTO `tb_employee` VALUES (3, '小AA', '234234@qq.com', '1', 18);
INSERT INTO `tb_employee` VALUES (4, 'White', 'white@163.com', '0', 35);

SET FOREIGN_KEY_CHECKS = 1;

2、创建一个空的maven项目

3、添加maven的依赖信息

特别说明: Mybatis依赖请勿加入项目配置,以免引起版本冲突!!!

Mybatis-Plus 会自动帮你维护!MyBatisPlus包是一个综合包(包含MyBatis包,不用再导入一遍的!)

        <!-- lombok--> 
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
        </dependency>

        <!-- MyBatis plus 包含了MyBatis-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus</artifactId>
            <version>3.1.1</version>
        </dependency>

        <!-- mysql驱动包 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.25</version>
        </dependency>

        <!-- Junit测试 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

4、编写配置文件,连接数据库 

jdbc.driverName=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/mybatis-db-2?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&useSSL=false
jdbc.username=root
jdbc.password=123456

5、加入 MyBatis 的全局配置文件

<?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>

    <!--引入外部的属性文件-->
    <properties resource="db.properties"/>

    <!--MyBatis开启运行SQL日志-->
    <settings>
        <setting name="logImpl" value="org.apache.ibatis.logging.stdout.StdOutImpl"/>
        <!-- localCacheScope是本地缓存(一级缓存)的作用域,只有两种取值:SESSION和STATEMENT 语句级别,取STATEMENT意味着关闭一级缓存-->
        <setting name="localCacheScope" value="SESSION"/>
        <!-- cacheEnabled是二是级缓存的总开关,置为false代表关闭二级缓存  全局开关 -->
        <setting name="cacheEnabled" value="true"/>
    </settings>

    <!--全局配置:实体类取别名-->
    <typeAliases>
        <!--一次性给下面所有的包下的类取别名 默认别名就是类名(不区分大小写 Users users)-->
        <package name="com.it.pojo"/>
    </typeAliases>

    <!--当前使用的MyBatis数据库环境-->
    <environments default="mysql">
        <!--mysql数据库环境-->
        <environment id="mysql">
            <!--JDBC事务管理-->
            <transactionManager type="JDBC"/>
            <!--MyBatis框架底层自带的数据库连接池 POOLED-->
            <dataSource type="POOLED">
                <!--数据库驱动-->
                <property name="driver" value="${jdbc.driverName}"/>
                <!-- 数据库连接字符串-->
                <property name="url" value="${jdbc.url}"/>
                <!-- 数据库连接账号-->
                <property name="username" value="${jdbc.username}"/>
                <!-- 数据库连接密码-->
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <!--映射Mapper文件-->
        <!--com.it.mapper包下自动定位xml-->
        <package name="com.it.mapper"/>
    </mappers>

</configuration>

6、创建mybatis的工具类(这里mybatis plus使用的工具类与之前用的mybatis的类似,唯一的区别就是sqlSessioFactory的创建有所不同)

//织入MyBatisPlus,SqlSessionFactoryBuilder替换为类:MybatisSqlSessionFactoryBuilder
        

 区别点: sqlSessionFactory = new MybatisSqlSessionFactoryBuilder().build(reader);

/**
 * 封装MyBatis工具类
 */
public class MyBatisUtils {

    private static SqlSessionFactory sqlSessionFactory = null;

    /**
     * 静态代码块执行一次,性能高 初始化sqlSessionFactory
     */
    static {
        try {
            String resource = "mybatis-config.xml";
            Reader reader = Resources.getResourceAsReader(resource);
            //织入MyBatisPlus,SqlSessionFactoryBuilder替换为子类:MybatisSqlSessionFactoryBuilder
            sqlSessionFactory = new MybatisSqlSessionFactoryBuilder().build(reader);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //1.定义Threadlocal存储类型为SqlSession
    private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>();

    /**
     * 获取 SqlSession 对象的静态方法
     */
    public static SqlSession getSqlSession() {
        //2.从线程里面获取共享的SqlSession对象
        SqlSession sqlSession = threadLocal.get();
        //3.对象为空,创建一个新的sqlSession写入线程共享ThreadLocal中
        if (sqlSession == null) {
            sqlSession = sqlSessionFactory.openSession(true); // true 表示自动提交事务  false 手动提交事务
            threadLocal.set(sqlSession);
        }
        //4.返回有效对象
        return sqlSession;
    }

    /**
     * 关闭sqlSession
     *
     * @param sqlSession
     */
    public static void closeSqlsession(SqlSession sqlSession) {
        sqlSession.close();
        //从线程共享变量里面移出sqlSession
        threadLocal.remove();
    }

    //根据给定的接口类型直接返回接口代理对象
    public static <T> T getMapper(Class<T> interfaceClass) {
        //MyBatis JDK动态代理设计模式: 可以根据接口 给这个接口自动生成一个实现类(代理类)
        return getSqlSession().getMapper(interfaceClass);
    }
}

7、创建pojo类、mapper接口以及mapper.xml文件

传统方式(不适用mybatis plus情况下):

        创建pojo——>dao(连接mybatis,创建mapper接口配置mapper.xml文件)-service-controller


使用了mybatis-plus之后(继承BaseMapper接口,BaseMapper里面定义了17个常用的持久层方法,使用BaseMapper里定义的方法时不用添加mapper.xml文件),但是如果不使用BaseMapper里面的方法,自己在接口中定义方法的时候需要mapper.xml文件里面添加对应方法的sql语句。

 pojo的创建

@Data
@NoArgsConstructor
@AllArgsConstructor
@TableName(value = "tb_employee") //默认表名和类名相同,如果不同用注解说明
public class Employee implements Serializable {
        
    //实现序列化、mybatis二级缓存
    private static final long serialVersionUID = -5150219292948138785L;

    //标识主键自增
    @TableId(value = "ID",type = IdType.AUTO)
    private Integer id;

    @TableField(value = "LAST_NAME")
    private String lastName;

    @TableField(value = "EMAIL")
    private String email;

    //数据表字段说明,value的值为数据表里面对应的数据字段,如果一致可以不用加该注解
    @TableField(value = "GENDER")
    private String sex;

    @TableField(value = "AGE")
    private Integer age;
}

mapper接口 

/**
 *  BaseMapper<T>:泛型指定的就是当前Mapper接口所操作的实体类类型
 *  其中有十几个已经定义好的方法
 */
public interface EmployeeMapper extends BaseMapper<Employee> {

    Employee finEmployeeById(Integer id);

    int updateEmployee(Employee employe);

    //...... 如果MyBatis Plus方法不够用,可以自己写!MyBatis pLus只增强
}

mapper.xml文件 

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.it.mapper.EmployeeMapper">

    <cache/>

    <resultMap id="empMap" type="employee">
        <id column="ID" property="id"/>
        <result column="last_name" property="lastName"/>
        <result column="email" property="email"/>
        <result column="gender" property="sex"/>
        <result column="age" property="age"/>
    </resultMap>

    <select id="finEmployeeById" resultMap="empMap" useCache="true">
         select * from tb_employee where id=#{id}
    </select>

    <update id="updateEmployee" flushCache="true">
        update tb_employee
        <set>
            <if test="lastName!=null and lastName!=''">
                last_name=#{lastName},
            </if>
            <if test="email!=null and email!=''">
                email=#{email},
            </if>
            <if test="gender!=null and gender!=''">
                gender=#{gender},
            </if>
            <if test="age!=null">
                age=#{age},
            </if>
        </set>
        where id=#{id}
    </update>

</mapper>

3、Mapper CRUD 接口

一旦继承BaseMapper<Employee>之后,系统内置了有十几个CRUD相关的方法,这些方法可以直接使用,不用自己来定义!

在MyBatis Plus的底层。这些接口的SQL语句是自动生成的,不需要去管SQL语句!说白了,直接调用就可以!

Insert

// 插入一条记录
int insert(T entity);

 测试1:

    @Test
    public void testInsert() {
        int count = employeeMapper.insert(new Employee(null, "小AA", "234234@qq.com", "1", 18));
        System.out.println(count > 0 ? "新增成功" : "新增失败");
    }

Delete

// 根据 entity 条件,删除记录
int delete(@Param(Constants.WRAPPER) Wrapper<T> wrapper);
// 删除(根据ID 批量删除)
int deleteBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);
// 根据 ID 删除
int deleteById(Serializable id);
// 根据 columnMap 条件,删除记录
int deleteByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);

Update

// 根据 whereWrapper 条件,更新记录
int update(@Param(Constants.ENTITY) T updateEntity, @Param(Constants.WRAPPER) Wrapper<T> whereWrapper);
// 根据 ID 修改
int updateById(@Param(Constants.ENTITY) T entity);

Select

// 根据 ID 查询
T selectById(Serializable id);
// 根据 entity 条件,查询一条记录
T selectOne(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

// 查询(根据ID 批量查询)
List<T> selectBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);
// 根据 entity 条件,查询全部记录
List<T> selectList(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
// 查询(根据 columnMap 条件)
List<T> selectByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);
// 根据 Wrapper 条件,查询全部记录
List<Map<String, Object>> selectMaps(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
// 根据 Wrapper 条件,查询全部记录。注意: 只返回第一个字段的值
List<Object> selectObjs(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

// 根据 entity 条件,查询全部记录(并翻页)
IPage<T> selectPage(IPage<T> page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
// 根据 Wrapper 条件,查询全部记录(并翻页)
IPage<Map<String, Object>> selectMapsPage(IPage<T> page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
// 根据 Wrapper 条件,查询总记录数
Integer selectCount(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

李仙桎

你的鼓励是我创作最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值