欢迎访问宙启技术站
智能推送

使用MyBatis Plus实现整合封装——SpringBoot篇

发布时间:2023-05-16 23:27:19

MyBatis Plus是MyBatis的增强工具,通过封装了MyBatis的常用操作,提供了更加方便快捷的使用方式。

在SpringBoot项目中使用MyBatis Plus,可以通过以下步骤实现整合封装:

1. 引入依赖

在使用SpringBoot项目中,只需要在pom.xml文件中添加如下依赖即可:

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

2. 配置数据源

在application.properties中配置数据源信息:

spring.datasource.url=jdbc:mysql://localhost:3306/demo?useUnicode=true&useSSL=false&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

3. 配置MyBatis Plus

使用MyBatis Plus需要配置MybatisPlusConfig类,示例代码如下:

@Configuration
@MapperScan("com.example.demo.mapper")
public class MybatisPlusConfig {
 
    /**
     * 分页插件
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }
 
    /**
     * 自动填充字段
     */
    @Bean
    public MetaObjectHandler metaObjectHandler() {
        return new MyMetaObjectHandler();
    }
 
}

其中,@MapperScan注解指定扫描的Mapper包路径,PaginationInterceptor用于分页操作,MyMetaObjectHandler用于自动填充字段。

4. 创建实体类和Mapper接口

在创建实体类时需要使用MyBatis Plus提供的注解,例如@TableName用于指定表名,@TableField用于指定字段名等等。

Mapper接口需要继承BaseMapper,MyBatis Plus会自动生成常用的CRUD方法,例如insertupdatedeleteselectById等。

示例代码如下:

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

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

5. 使用实体类和Mapper接口

创建完实体类和Mapper接口后,可以在Service或Controller中使用它们提供的方法进行数据库操作。

示例代码如下:

@Service
public class UserServiceImpl implements UserService {
 
    @Autowired
    private UserMapper userMapper;
 
    @Override
    public List<User> findAll() {
        return userMapper.selectList(null);
    }
 
    @Override
    public User findById(Long id) {
        return userMapper.selectById(id);
    }
 
    @Override
    public void save(User user) {
        userMapper.insert(user);
    }
 
    @Override
    public void update(User user) {
        userMapper.updateById(user);
    }
 
    @Override
    public void deleteById(Long id) {
        userMapper.deleteById(id);
    }
 
}

使用MyBatis Plus可以大大简化数据库操作的代码,提高开发效率。同时,MyBatis Plus提供的很多特性,如分页、自动填充、乐观锁等等也能极大地提高开发效率。