【快速学习】SpringBoot整合MyBatis Plus

目录

官方文档地址:

1、相关pom.xml依赖

2、相关包通用实现

3、相关注解

4、增删查改

5、MyBatis Plus的分页


官方文档地址:

https://mp.baomidou.com/guide/

MyBatis Plus 其实就是MyBatis的一个增强工具包,只做增强,不做改变。

对普通的CRUD方法可以直接调用MyBatis Plus的CRUD方法。简化开发。

这里直接是SpringBoot整合MyBatis Plus

1、相关pom.xml依赖

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

<dependency>
     <groupId>com.h2database</groupId>
     <artifactId>h2</artifactId>
     <scope>runtime</scope>
</dependency>
    
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
</dependency>

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.23</version>
</dependency>
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql:///testdb?useUnicode=true&characterEncoding=UTF8&useSSL=false
spring.datasource.username=root
spring.datasource.password=root

2、相关包通用实现

MyBatis Plus支持数据库,比如:mysql,oracle,sqlServer等。

可以在SpringBoot的主配置文件下扫描Dao包:@MapperScan(value="...")

@SpringBootApplication
@MapperScan(value = "com.test.mybatisplus.mapper")
public class MybatisplusApplication {
    public static void main(String[] args) {
        SpringApplication.run(MybatisplusApplication.class, args);
    }
}
// Dao层:
继承BaseMapper,实现CRUD方法的继承
public interface UserMapper extends BaseMapper<User> {

}
//BaseMapper中的CRUD方法
public interface BaseMapper<T> extends Mapper<T> {
    int insert(T entity);

    int deleteById(Serializable id);

    int deleteByMap(@Param("cm") Map<String, Object> columnMap);

    int delete(@Param("ew") Wrapper<T> queryWrapper);

    int deleteBatchIds(@Param("coll") Collection<? extends Serializable> idList);

    int updateById(@Param("et") T entity);

    int update(@Param("et") T entity, @Param("ew") Wrapper<T> updateWrapper);

    T selectById(Serializable id);

    List<T> selectBatchIds(@Param("coll") Collection<? extends Serializable> idList);

    List<T> selectByMap(@Param("cm") Map<String, Object> columnMap);

    T selectOne(@Param("ew") Wrapper<T> queryWrapper);

    Integer selectCount(@Param("ew") Wrapper<T> queryWrapper);

    List<T> selectList(@Param("ew") Wrapper<T> queryWrapper);

    List<Map<String, Object>> selectMaps(@Param("ew") Wrapper<T> queryWrapper);

    List<Object> selectObjs(@Param("ew") Wrapper<T> queryWrapper);

    <E extends IPage<T>> E selectPage(E page, @Param("ew") Wrapper<T> queryWrapper);

    <E extends IPage<Map<String, Object>>> E selectMapsPage(E page, @Param("ew") Wrapper<T> queryWrapper);
}

3、相关注解

①:@TableName:描述的是实体类的名字和表的名字之间的映射

// 表名是t_user,实体类名是 User,添加注解可以实现映射
@TableName(value="t_user")
public class User{}

②:@TableId:代表告诉MybatisPlus中,哪个实体类的字段名为表的主键。当实体类名的id名字 和表字段的id对应的时候,那么就会自动找到主键对应。

public class User{
    @TableId("user_id")
    private Integer id;
}

@TableField:数据库中是name,实体类中是userName。

// 表中的是username,实体类中的是name

public class User{

@TableField(value="username")
private Integer name;

}

4、增删查改

这儿使用的是Controller层进行操作的。

下面代码注释详细:

/**
     * 查询所有
     */
    @RequestMapping("/findAllUser")
    public List<User> findAllUser() {
        List<User> userList = userMapper.selectList(null);
        return userList;
    }

    /**
     * 通过id查询,查询单条数据
     *
     * @param id
     * @return
     */
    @GetMapping("/findUserById")
    public User findUserById(@RequestParam int id) {
        User user = userMapper.selectById(id);
        return user;
    }

    /**
     * 条件查询
     */
    @GetMapping("/findUserByCondition")
    public List<User> findUserByCondition(@RequestParam String column, @RequestParam Object val) {
        // queryWrapper 添加查询条件
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        // 等值查询
//        queryWrapper.eq(column,val);

        // 小于
//        queryWrapper.lt(column, val);

        // 小于等于
        queryWrapper.le(column, val);

        // gt 大于
        // ge 大于等于


        // selectList,添加查询条件
        List<User> userList = userMapper.selectList(queryWrapper);
        return userList;
    }

    /**
     * 模糊查询
     */

    @GetMapping("/queryString")
    public List<User> queryString(@RequestParam String column, @RequestParam Object val) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        // select * from table where column like %?%
//        queryWrapperyWrapper.like(column, val);
        // likeLeft   %? :以?为结尾的
//        queryWrapper.likeLeft(column, val);
        // likeRight  ?%:以 ?为开头的
        queryWrapper.likeRight(column, val);
        List<User> list = userMapper.selectList(queryWrapper);
        return list;
    }

    /**
     * 插入数据
     */
    @RequestMapping("/insertData")
    public void insertData() {
        User user = new User();
        user.setId(9).setName("zhangsan").setAge(18).setEmail("shitianen.com");

        userMapper.insert(user);
    }

    /**
     * 基于ID进行修改
     */
    @RequestMapping("/updateById")
    public void updateById() {
        // 先拿到这个id的数据
        User user = userMapper.selectById("5");
        user.setName("wangcancan");
        // 更新user
        userMapper.updateById(user);
    }

    /**
     * 批量修改
     * 把age = 12的全部修改成谢霆锋
     */
    @RequestMapping("/updateBatch")
    public void updateBatch() {
        // 先查
        User entity = new User();
        entity.setName("谢霆锋");
        QueryWrapper<User> updateWrapper = new QueryWrapper<>();
        updateWrapper.eq("age", 12);
        // 将entity对象设置的setName传进去,然后根据这个
        userMapper.update(entity, updateWrapper);
    }

    /**
     * 删除 根据id进行删除
     */
    @RequestMapping("/deleteById")
    public void deleteById() {
        userMapper.deleteById("5");
    }

    /**
     * 批量删除
     */
    @RequestMapping("/deleteBatch")
    public void deleteBatch(){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.gt("age", 15);
        userMapper.delete(queryWrapper);
    }

注意:这里有条件构造器:queryWrapper,queryWrapper是mybatis plus中实现查询的对象封装操作类。

QueryWrapper中的方法:

5、MyBatis Plus的分页

首先配置MyBatis Plus的分页配置类

@EnableTransactionManagement   // 事务的配置
@Configuration
@MapperScan("com.test.mybatisplus.mapper")  扫描Mapper接口,也就是数据源
public class config {
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        // 设置请求的页面大于最大页后操作, true调回到首页,false 继续请求  默认false
        // paginationInterceptor.setOverflow(false);
        // 设置最大单页限制数量,默认 500 条,-1 不受限制
        // paginationInterceptor.setLimit(500);
        // 开启 count 的 join 优化,只针对部分 left join
        paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true));
        return paginationInterceptor;
    }
}
  /**
     * 分页插件的使用,单条数据分页
     */
    @RequestMapping("/page")
    public void findPage() {
        // 具体的信息
        IPage<User> page = new Page<>(1, 2);
        // 返回一个全部分页的结果
        IPage<User> userIPage = userMapper.selectPage(page, null);

        // 获取总的记录数,数据库表中数据的条数
        long total = userIPage.getTotal();
        System.out.println("总记录数" + total);

        // 遍历记录
        userIPage.getRecords().forEach(user -> {
            System.out.println("user =" + user);
        });
    }
/**
     * 待条件的分页擦汗寻
     */
    @RequestMapping("/pageCondition")
    public void pageCondition(){

        // 添加一个条件信息
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("age", 12);

        // 设置当前页,每页显示的条数
        IPage<User> page = new Page<>(1, 2);
        IPage<User> userIPage = userMapper.selectPage(page, queryWrapper);
        System.out.println("总条数" + userIPage.getTotal());

        // 遍历每页内容,user 是User中的对象
        userIPage.getRecords().forEach(user -> {
            System.out.println("user =" + user);
        });
    }

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值