MyBatisPlus学习笔记【part1】

导读:本篇文章讲解 MyBatisPlus学习笔记【part1】,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

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 不配置主键策略,即跟随全局,也就是雪花算法
INPUT insert前用户自行输入
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);
}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由半码博客整理,本文链接:https://www.bmabk.com/index.php/post/84469.html

(0)
小半的头像小半

相关推荐

半码博客——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!