Mybatis-plus对单表操作的封装

27 篇文章 0 订阅
19 篇文章 0 订阅

MyBatis-Plus单表操作详解及拓展

MyBatis-Plus是一个基于MyBatis的增强工具,它提供了丰富的CRUD操作和分页查询等功能,极大地简化了开发人员的数据库操作。本文将详细介绍MyBatis-Plus官方已经写好的单表操作,并提供一些拓展内容。

1. 引言

在进行单表操作之前,我们需要定义一个实体类和对应的Mapper接口。以下是一个简单的实体类和Mapper接口示例:

@Data
@TableName("user")
public class User {
    @TableId(type = IdType.AUTO)
    private Long id;
    private String username;
    private String password;
    private Integer age;
}

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

在实体类上使用@TableName注解指定对应的数据库表名,使用@TableId注解指定主键字段。在Mapper接口上使用@Mapper注解标识该接口为Mapper接口,并继承BaseMapper<User>,这样就可以直接使用MyBatis-Plus提供的CRUD操作方法。

2. 单表操作

2.1 插入操作

插入操作可以使用insert方法,示例代码如下:

User user = new User();
user.setUsername("Tom");
user.setPassword("123456");
user.setAge(18);

UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
int result = userMapper.insert(user);
if (result > 0) {
    System.out.println("插入成功");
}

2.2 查询操作

查询操作可以使用selectByIdselectListselectPage等方法,示例代码如下:

UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

// 根据ID查询
User user = userMapper.selectById(1L);

// 根据条件查询
LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(User::getUsername, "Tom");
List<User> userList = userMapper.selectList(queryWrapper);

// 分页查询
Page<User> page = new Page<>(1, 10);
LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.orderByDesc(User::getAge);
IPage<User> resultPage = userMapper.selectPage(page, queryWrapper);
List<User> userList = resultPage.getRecords();

2.3 更新操作

更新操作可以使用updateById方法,示例代码如下:

User user = new User();
user.setId(1L);
user.setUsername("Jerry");
user.setPassword("654321");
user.setAge(20);

UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
int result = userMapper.updateById(user);
if (result > 0) {
    System.out.println("更新成功");
}

2.4 删除操作

删除操作可以使用deleteByIddeleteBatchIdsdelete等方法,示例代码如下:

UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

// 根据ID删除
int result = userMapper.deleteById(1L);
if (result > 0) {
    System.out.println("删除成功");
}

// 根据条件删除
LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.eq(User::getUsername, "Tom");
int result = userMapper.delete(queryWrapper);
if (result > 0) {
    System.out.println("删除成功");
}

3. 拓展内容

除了官方提供的基本CRUD操作外,MyBatis-Plus还提供了许多其他功能和拓展,以下是一些常用的拓展内容:

3.1 自定义SQL

如果需要自定义SQL语句,可以使用BaseMapper提供的selectListselectByIdinsertupdateByIddeleteById等方法的重载版本,传入Wrapper对象和RowBounds对象进行自定义查询和分页。

UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

// 自定义SQL查询
LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
queryWrapper.select(User::getId, User::getUsername)
            .orderByAsc(User::getAge);
List<User> userList = userMapper.selectList(queryWrapper, new RowBounds(0, 10));

// 自定义SQL插入
User user = new User();
user.setUsername("CustomUser");
user.setPassword("password");
user.setAge(25);
int result = userMapper.insert(user, new InsertWrapper<User>().setSql("INSERT INTO user(username, password, age) VALUES(#{username}, #{password}, #{age})"));

// 自定义SQL更新
User updateUser = new User();
updateUser.setId(1L);
updateUser.setUsername("UpdatedUser");
updateUser.setPassword("updatedPassword");
int result = userMapper.updateById(updateUser, new UpdateWrapper<User>

3.2 逻辑删除

MyBatis-Plus提供了逻辑删除功能,可以通过配置实体类和数据库表字段实现。逻辑删除是指在数据库中将记录的删除标志位设置为已删除,而不是物理删除记录。这样可以避免误删除数据,同时也可以满足一些特殊需求,例如数据恢复、数据审计等。

要使用逻辑删除功能,需要在实体类上使用@TableLogic注解标识删除标志位字段,并在Mapper接口上使用@Mapper注解的logicDelete属性启用逻辑删除功能。示例代码如下:

@Data
@TableName("user")
@TableLogic(value = "deleted", delval = "1")
public class User {
    @TableId(type = IdType.AUTO)
    private Long id;
    private String username;
    private String password;
    private Integer age;
    private Integer deleted;
}

@Mapper(logicDelete = true)
public interface UserMapper extends BaseMapper<User> {
}

在实体类上使用@TableLogic注解指定删除标志位字段和已删除值,在Mapper接口上使用@Mapper注解的logicDelete属性启用逻辑删除功能。这样就可以使用deleteByIddeleteBatchIdsdelete等方法进行逻辑删除操作。

3.3 乐观锁

MyBatis-Plus提供了乐观锁功能,可以通过配置实体类和数据库表字段实现。乐观锁是一种并发控制策略,它假设多个事务并发执行时不会发生冲突,每个事务在提交时都会验证其操作的数据是否已经被其他事务修改过。如果发现数据已经被修改,则当前事务会回滚,避免了数据不一致的问题。

要使用乐观锁功能,需要在实体类上使用@Version注解标识版本号字段,并在Mapper接口上使用@Mapper注解的optimisticLocker属性启用乐观锁功能。示例代码如下:

@Data
@TableName("user")
@Version
public class User {
    @TableId(type = IdType.AUTO)
    private Long id;
    private String username;
    private String password;
    private Integer age;
    private Integer version;
}

@Mapper(optimisticLocker = true)
public interface UserMapper extends BaseMapper<User> {
}

在实体类上使用@Version注解标识版本号字段,在Mapper接口上使用@Mapper注解的optimisticLocker属性启用乐观锁功能。这样就可以使用updateById等方法进行乐观锁更新操作。

3.4 全局拦截器

MyBatis-Plus提供了全局拦截器功能,可以通过实现Interceptor接口自定义拦截器,并在配置文件中注册拦截器。全局拦截器可以拦截所有的SQL语句,并在SQL执行前后进行一些自定义操作,例如记录日志、权限校验等。

示例代码如下:

@Component
@Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})})
public class MyInterceptor implements Interceptor {
    @Override
    public InterceptResult intercept(Invocation invocation) throws Throwable {
        // 在SQL执行前进行一些自定义操作
        System.out.println("Before SQL: " + invocation.getTarget());

        // 执行SQL语句
        Object result = invocation.proceed();

        // 在SQL执行后进行一些自定义操作
        System.out.println("After SQL: " + invocation.getTarget());

        return InterceptResult.success(result);
    }
}

实现Interceptor接口,并使用@Intercepts注解标识拦截的方法和参数类型。在intercept方法中进行自定义操作,并使用invocation.proceed()执行SQL语句。最后返回InterceptResult.success(result)表示拦截器执行成功。

在配置文件中注册拦截器,示例代码如下:

<mybatis-plus>
    <configuration>
        <interceptors>
            <interceptor class="com.example.MyInterceptor"/>
        </interceptors>
    </configuration>
</mybatis-plus>

mybatis-plus标签中配置configuration标签,在configuration标签中配置interceptors标签,在interceptors标签中配置自定义拦截器类。

3.5 代码生成器

MyBatis-Plus提供了代码生成器功能,可以通过配置文件自动生成实体类、Mapper接口、Service接口和Controller接口等代码。代码生成器可以大大提高开发效率,避免重复劳动。

示例代码如下:

<mybatis-plus-generator>
    <global-config>
        <output-dir>D:\code\mybatis-plus-generator\src\main\java</output-dir>
        <author>zhangsan</author>
        <open>false</open>
    </global-config>
    <data-source>
        <url>jdbc:mysql://localhost:3306/mybatis_plus</url>
        <username>root</username>
        <password>123456</password>
        <driver-class-name>com.mysql.jdbc.Driver</driver-class-name>
    </data-source>
    <package-info>
        <module-name>user</module-name>
        <parent>com.example</parent>
    </package-info>
    <strategy>
        <table-prefix>t_</table-prefix>
        <entity-lombok-model>true</entity-lombok-model>
        <rest-controller-style>true</rest-controller-style>
        <controller-mapping-hyphen-style>true</controller-mapping-hyphen-style>
        <include>t_user</include>
    </strategy>
</mybatis-plus-generator>

mybatis-plus-generator标签中配置代码生成器的全局配置、数据源配置、包信息配置和策略配置。在global-config标签中配置输出目录、作者信息和是否自动打开生成的文件夹。在data-source标签中配置数据库连接信息。在package-info标签中配置包名信息。在strategy标签中配置表名前缀、实体类是否使用Lombok注解、Controller接口是否使用RESTful风格和需要生成的表名。

运行代码生成器后,会自动生成实体类、Mapper接口、Service接口和Controller接口等代码。

4. 总结

MyBatis-Plus是一个非常强大的ORM框架,它提供了丰富的CRUD操作和分页查询等功能,同时也提供了许多其他功能和拓展,例如自定义SQL、逻辑删除、乐观锁、全局拦截器和代码生成器等。使用MyBatis-Plus可以大大提高开发效率,同时也可以满足一些特殊需求。

  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

five-five

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

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

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

打赏作者

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

抵扣说明:

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

余额充值