MyBatisPlus学习笔记【part1】

MyBatis-Plus是MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。

一、前置工作

1.引入依赖。

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

2.在 application.properties 配置文件中添加 MySQL 数据库的相关配置。

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus?serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=123456

其中,这里的 url 使用了 ?serverTimezone=GMT%2B8 后缀,因为8.0版本的jdbc驱动需要添加这个后缀,否则运行测试用例将报错。这里的 driver-class-name 使用了 com.mysql.cj.jdbc.Driver,在 jdbc 8中建议使用这个驱动,否则运行测试用例的时候会有 WARN 信息。

3.添加mapper,继承BaseMapper并补充泛型。

@Repository
public interface UserMapper extends BaseMapper<User> {
}

/*      
@Repository和@Mapper都是用在dao层上的注解,标记为持久层,不过使用上也会有区别
@Repository是spring的注解,标记为一个bean,配合mybatis时需要配置@MapperScan
@Mapper是mybatis的注解,不需要额外的@MapperScan扫描.
*/

并在主程序中添加mapper包扫描。

@SpringBootApplication
@MapperScan(basePackages = "com.ichuang.swz.mapper")
public class SwzApplication {
    public static void main(String[] args) {
        SpringApplication.run(SwzApplication.class, args);
    }
}

4.接下来进行单元测试,成功输出结果,完成了基本配置和快速入门。

@Slf4j
@SpringBootTest
class SwzApplicationTests {

    @Autowired
    private UserMapper userMapper;

    @Test
    public void selectAll(){
        List<User> users = userMapper.selectList(null);
        for (User user : users) {
            log.info(user.toString());
        }
    }

}

二、主键策略

在springboot配置文件中添加,即可开启mybatis日志,这样的话可以在日志信息中查看到mybatis_plus自动生成的sql语句。

#mybatis日志
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
1.插入操作

使用insert方法。

    @Test
    public void testAdd() {
        User user = new User();
        user.setName("zhangsan");
        user.setAge(30);
        user.setEmail("123@qq.com");
        int i = userMapper.insert(user);
        System.out.println(i);
    }
2.MybatisPlus的主键策略

MyBatis-Plus默认的主键策略是:ASSIGN_ID (使用了雪花算法)

雪花算法是分布式ID生成器,能够保证不同表的主键的不重复性,以及相同表的主键的有序性,整体上按照时间自增排序,并且整个分布式系统内不会产生ID碰撞,并且效率较高。

作用
AUTO数据库ID自增
NULL不配置主键策略,即跟随全局,也就是雪花算法
INPUTinsert前用户自行输入
ASSIGN_ID雪花算法生成
ASSIGN_UUID分配UUID

单个实体中配置如下。

@Data
public class User {
    @TableId(type = IdType.AUTO)
    private Long id;
    
    private String name;
    private Integer age;
    private String email;
}

全局配置如下。

#全局设置主键生成策略
mybatis-plus.global-config.db-config.id-type=auto

三、自动填充

1.更新操作

updateById方法,参数传入整个实体。update时生成的sql自动是动态sql:UPDATE user SET name=? WHERE id=?

@Test
public void testUpdate() {
    User user = new User();
    user.setId(1613767658091577345L);
    user.setName("lisi");
    int i = userMapper.updateById(user);
    System.out.println(i);
}
2.自动填充

项目中经常会遇到一些数据,每次都使用相同的方式填充,例如记录的创建时间,更新时间等。我们可以使用MyBatis Plus的自动填充功能,完成这些字段的赋值工作。

第一步,添加自动填充注解。

@TableField(fill = FieldFill.INSERT)
private Date createTime;

@TableField(fill = FieldFill.INSERT_UPDATE)
private Date updateTime;

第二步,实现元对象处理器接口。

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    //mybatis_plus执行添加操作,这个方法执行
    @Override
    public void insertFill(MetaObject metaObject) {
        this.setFieldValByName("createTime",new Date(),metaObject);
        this.setFieldValByName("updateTime",new Date(),metaObject);
    }

    //mybatis_plus执行更新操作,这个方法执行
    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName("updateTime",new Date(),metaObject);
    }
}

第三步,单元测试。

@Test
public void testAdd() {
    User user = new User();
    user.setName("zhangsan10");
    user.setAge(18);
    user.setEmail("888@qq.com");
    int i = userMapper.insert(user);
    System.out.println(i);
}

@Test
public void testUpdate() {
    User user = new User();
    user.setId(1613776095357759489L);
    user.setName("zhangsan7");
    int i = userMapper.updateById(user);
    System.out.println(i);
}

四、乐观锁

当要更新一条记录的时候,希望这条记录没有被别人更新,也就是说实现线程安全的数据更新。例如,张三和李四同时对员工工资进行了修改,这时会发生丢失更新。

乐观锁的原理
取出记录时,获取当前version。
更新时,带上这个version。
执行更新时, set version = newVersion where version = oldVersion ,如果version不对,就更新失败。

乐观锁的实现流程。

第一步,添加@Version注解。

@Version
@TableField(fill = FieldFill.INSERT)
private Integer version;

第二步,在配置文件中注册乐观锁插件。

@Configuration
@MapperScan(basePackages = "com.ichuang.swz.mapper")  //把主类中的 @MapperScan 扫描注解删除,以后统一放在mybatis_plus的配置类中
public class MybatisPlusConfig {

    /*
     * 乐观锁插件,新版本配置办法
     */
    @Bean
    public MybatisPlusInterceptor optimisticLockerInnerInterceptor(){
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        mybatisPlusInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        return mybatisPlusInterceptor;
    }
}

第三步,配置自动填充。

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    //mybatis_plus执行添加操作,这个方法执行
    @Override
    public void insertFill(MetaObject metaObject) {
        this.setFieldValByName("version",1,metaObject);
    }

    //mybatis_plus执行更新操作,这个方法执行
    @Override
    public void updateFill(MetaObject metaObject) {
        //修改操作无需配置,乐观锁自己完成。
    }
}

第四步,单元测试。

@Test
public void testAdd() {
    User user = new User();
    user.setName("lisi10");
    user.setAge(25);
    user.setEmail("333@qq.com");
    int i = userMapper.insert(user);
    System.out.println(i);
}

@Test
public void testUpdate() {
    User user = userMapper.selectById(1613780561515573250L);
    user.setName("lisi7");
    user.setAge(18);
    int i = userMapper.updateById(user);
    System.out.println(i);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Parker7

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

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

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

打赏作者

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

抵扣说明:

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

余额充值