代码编织梦想

一、SpringBoot集成Mybatis-Plus方法

  1. 创建springboot项目

    image-20220427222337290

    这里可以选择MySQL坐标,也可以不选然后自己手动添加

    image-20220427222500038

  2. 添加依赖

            <!--mybatis-plus-->
            <dependency>
                <groupId>com.baomidou</groupId>
                <artifactId>mybatis-plus-boot-starter</artifactId>
                <version>3.5.0</version>
            </dependency>
    
            <!--MySQL依赖-->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <scope>runtime</scope>
            </dependency>
            
            <!--druid-->
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid-spring-boot-starter</artifactId>
                <version>1.2.9</version>
            </dependency>
            
            <!--lombok-->
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
            </dependency>
    
  3. 在application.yml中配置数据库

    server:
      port: 8080
      servlet:
        context-path: /
    spring:
      datasource:
        druid:   #数据源使用druid
          driver-class-name: com.mysql.cj.jdbc.Driver
          url: jdbc:mysql://localhost:3306/ssm_db?useUnicode=true&characterEncoding=UTF-8&useJDBC49CompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8
          username: root
          password: root
    
  4. 使用Lombok创建实体类

    Book实体类:
    @Data
    public class Book {
        private Integer id;
        private String type;
        private String name;
        private String description;
    }
    
  5. 使用Mybatis-Plus创建dao层方法

    使用继承 BaseMapper<实体类>的方法,mp帮我们就创建了常用的sql

    import com.baomidou.mybatisplus.core.mapper.BaseMapper;
    import com.example.domain.Book;
    import org.apache.ibatis.annotations.Mapper;
    
    @Mapper
    public interface BookMapper extends BaseMapper<Book> {
    
    }
    
  6. 附:使用到的数据库的创建语句:

    SET NAMES utf8mb4;
    SET FOREIGN_KEY_CHECKS = 0;
    
    -- ----------------------------
    -- Table structure for book
    -- ----------------------------
    DROP TABLE IF EXISTS `book`;
    CREATE TABLE `book`  (
      `id` int(0) NOT NULL AUTO_INCREMENT,
      `type` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
      `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
      `description` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
      PRIMARY KEY (`id`) USING BTREE
    ) ENGINE = InnoDB AUTO_INCREMENT = 739889170 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
    
    SET FOREIGN_KEY_CHECKS = 1;
    
    

二、测试增删改查

    @Autowired
    private BookMapper bookMapper;
    //测试查询
    @Test
    void testGetById(){
        System.out.println(bookMapper.selectById(3));
    }
    //测试查询所有
    @Test
    void testGetAll(){
        System.out.println(bookMapper.selectList(null));
    }
    //测试保存
    @Test
    void testSave(){
        Book book = new Book();
        book.setName("汤家凤2023考研高数辅导书");
        book.setType("考研");
        book.setDescription("2023考研高数汤家凤");
        bookMapper.insert(book);
    }
    //测试修改
    @Test
    void testUpdate(){
        Book book = new Book();
        book.setId(739889166);
        book.setType("数学");
        bookMapper.updateById(book);

    }
    //测试删除
    @Test
    void testDelete(){
        bookMapper.deleteById(739889166);
    }

三、配置使用数据库默认id自增策略

mybatis-plus执行时对于id的处理默认是使用雪花算法随机生成id,但是我们在数据库表中给id设置的是自增(没有生效),设置默认使用数据库id自增策略的方式有两种

1.在application.yml配置文件中配置:

mybatis-plus:
  global-config:
    db-config:
      id-type: auto #使用数据库默认id自增策略

2.在实体类中使用注解@TableId(value = "id",type = IdType.AUTO)配置

//lombok
@Data  // = @Getter+@Setter
public class Book {
    @TableId(value = "id",type = IdType.AUTO)
    private Integer id;
    private String type;
    private String name;
    private String description;
}

四、开启Mybatis-plus日志

mybatis-plus执行时,默认是不显示执行过程以及执行的sql语句的,这样调试时很是不方便,所以要打开日志功能

在application.yml中开启mybatis-plus日志,设置日志显示方式为打印在控制台,配置代码如下:

mybatis-plus:
  global-config:
    db-config:
      id-type: auto #使用数据库默认id自增策略
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl  #日志打印到控制台

执行效果(显示完整的执行过程):

Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@1e4c6583] was not registered for synchronization because synchronization is not active
JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@76fe6cdc] will not be managed by Spring
==>  Preparing: SELECT id,type,name,description FROM book
==> Parameters: 
<==    Columns: id, type, name, description
<==        Row: -2019983359, 考研, 汤家凤2023考研高数辅导书, 2023考研高数汤家凤
<==        Row: -1986453503, 考研, 汤家凤2023考研高数辅导书, 2023考研高数汤家凤
<==        Row: -304508927, 考研, 汤家凤2023考研高数辅导书, 2023考研高数汤家凤
<==        Row: 1, 科技, Java编程思想, Java学习教程
<==        Row: 2, 科技, C++ primer plus, C++学习教程
<==        Row: 3, 人文, 阿甘正传, 在工作中学习
<==        Row: 4, 考研, 张宇高数18讲, 考研高数复习资料----张宇
<==        Row: 5, 考研, 句句真研, 田静考研英语
<==        Row: 739889167, 考研, 汤家凤2023考研高数辅导书, 2023考研高数汤家凤
<==        Row: 739889168, 考研, 汤家凤2023考研高数辅导书, 2023考研高数汤家凤
<==        Row: 739889169, 考研, 汤家凤2023考研高数辅导书, 2023考研高数汤家凤
<==      Total: 11
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@1e4c6583]

五、Mybatis-plus分页功能的实现

1.设定分页对象IPage

IPage ipage = new Page(2,5);
//执行分页查询
bookMapper.selectPage(ipage,null);

在这里插入图片描述

2.要想让上面的查询生效,还需要配置MyBatisPlus拦截器

在启动类的同级或上一级目录下新建config包,在config包中新建一个类命名为MPConfig.java(可以自己随意命名)

image-20220427200358774

在MPConfig中定义分页需要的拦截器,该拦截器会在执行查询时在sql语句后面添加LIMIT ?,?

@Configuration
public class MPConfig {
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor(){
        //1.定义mp拦截器
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        //2.添加指定的拦截器
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
        return interceptor;
    }

}

测试分页:

测试代码:
 @Test
    void testGetPage(){
        IPage ipage = new Page(2,5);
        //执行分页查询
        bookMapper.selectPage(ipage,null);
        System.out.println("当前页为: "+ipage.getCurrent());
        System.out.println("每一页的条数 "+ipage.getSize());
        System.out.println("表中数据总条数: "+ipage.getTotal());
        System.out.println("一共的页数: "+ipage.getPages());
        System.out.println("查到的数据: "+ipage.getRecords());
    }
测试结果:
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@1acb74ad] was not registered for synchronization because synchronization is not active
JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@21263314] will not be managed by Spring
==>  Preparing: SELECT COUNT(*) AS total FROM book
==> Parameters: 
<==    Columns: total
<==        Row: 11
<==      Total: 1
==>  Preparing: SELECT id,type,name,description FROM book LIMIT ?,?
==> Parameters: 5(Long), 5(Long)
<==    Columns: id, type, name, description
<==        Row: 3, 人文, 阿甘正传, 在工作中学习
<==        Row: 4, 考研, 张宇高数18讲, 考研高数复习资料----张宇
<==        Row: 5, 考研, 句句真研, 田静考研英语
<==        Row: 739889167, 考研, 汤家凤2023考研高数辅导书, 2023考研高数汤家凤
<==        Row: 739889168, 考研, 汤家凤2023考研高数辅导书, 2023考研高数汤家凤
<==      Total: 5
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@1acb74ad]
当前页为: 2
每一页的条数 5
表中数据总条数: 11
一共的页数: 3
查到的数据: [Book(id=3, type=人文, name=阿甘正传, description=在工作中学习), Book(id=4, type=考研, name=张宇高数18讲, description=考研高数复习资料----张宇), Book(id=5, type=考研, name=句句真研, description=田静考研英语), Book(id=739889167, type=考研, name=汤家凤2023考研高数辅导书, description=2023考研高数汤家凤), Book(id=739889168, type=考研, name=汤家凤2023考研高数辅导书, description=2023考研高数汤家凤)]

六、条件查询

1、方法一:QueryWrapper

@Test
    void testGetBy(){
        //1.新建QueryWrapper对象,Book是实体类
        QueryWrapper<Book> qw = new QueryWrapper<>();
        //2.条件
        qw.like("type","考研");
        //3.根据条件查询
        bookMapper.selectList(qw);
    }

运行结果:

Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@7cac93fe] was not registered for synchronization because synchronization is not active
JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@65a9ea3c] will not be managed by Spring
==>  Preparing: SELECT id,type,name,description FROM book WHERE (type LIKE ?)
==> Parameters: %考研%(String)
<==    Columns: id, type, name, description
<==        Row: -2019983359, 考研, 汤家凤2023考研高数辅导书, 2023考研高数汤家凤
<==        Row: -1986453503, 考研, 汤家凤2023考研高数辅导书, 2023考研高数汤家凤
<==        Row: -304508927, 考研, 汤家凤2023考研高数辅导书, 2023考研高数汤家凤
<==        Row: 4, 考研, 张宇高数18讲, 考研高数复习资料----张宇
<==        Row: 5, 考研, 句句真研, 田静考研英语
<==        Row: 739889167, 考研, 汤家凤2023考研高数辅导书, 2023考研高数汤家凤
<==        Row: 739889168, 考研, 汤家凤2023考研高数辅导书, 2023考研高数汤家凤
<==        Row: 739889169, 考研, 汤家凤2023考研高数辅导书, 2023考研高数汤家凤
<==      Total: 8
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@7cac93fe]

2、方法二LambdaQueryWrapper:

 @Test
    void testGetBy2(){
        //1.新建QueryWrapper对象
        LambdaQueryWrapper<Book> lqw = new LambdaQueryWrapper<>();
        //2.条件
        lqw.like(Book::getType,"汤家凤");
        //3.根据条件查询
        bookMapper.selectList(lqw);
    }

运行结果:

Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@2f14b0f6] was not registered for synchronization because synchronization is not active
JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@4c6b4ed7] will not be managed by Spring
==>  Preparing: SELECT id,type,name,description FROM book WHERE (name LIKE ?)
==> Parameters: %汤家凤%(String)
<==    Columns: id, type, name, description
<==        Row: -2019983359, 考研, 汤家凤2023考研高数辅导书, 2023考研高数汤家凤
<==        Row: -1986453503, 考研, 汤家凤2023考研高数辅导书, 2023考研高数汤家凤
<==        Row: -304508927, 考研, 汤家凤2023考研高数辅导书, 2023考研高数汤家凤
<==        Row: 739889167, 考研, 汤家凤2023考研高数辅导书, 2023考研高数汤家凤
<==        Row: 739889168, 考研, 汤家凤2023考研高数辅导书, 2023考研高数汤家凤
<==        Row: 739889169, 考研, 汤家凤2023考研高数辅导书, 2023考研高数汤家凤
<==      Total: 6
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@2f14b0f6]

使用LambdaQueryWrapper进行查询时,当参数为空时会出现错误,例如:

@Test
    void testGetBy2(){
        String name=null;
        //1.新建QueryWrapper对象
        LambdaQueryWrapper<Book> lqw = new LambdaQueryWrapper<>();
        //2.条件
        lqw.like(Book::getName,name);
        //3.根据条件查询
        bookMapper.selectList(lqw);
    }

运行结果:

image-20220427203000469

解决办法:判断参数是否为空

@Test
    void testGetBy2(){
        String name=null;
        //1.新建QueryWrapper对象
        LambdaQueryWrapper<Book> lqw = new LambdaQueryWrapper<>();
        //2.条件
        //if(name!=null) lqw.like(Book::getName,name);   //第一种解决参数为空的办法
        //第二种解决参数为空的方法
        lqw.like(name != null,Book::getName,name);
        //3.根据条件查询
        bookMapper.selectList(lqw);
    }

执行结果:(sql语句后面没有连接条件)

Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@4ace284d] was not registered for synchronization because synchronization is not active
JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@73aeef7d] will not be managed by Spring
==>  Preparing: SELECT id,type,name,description FROM book
==> Parameters: 
<==    Columns: id, type, name, description
<==        Row: -2019983359, 考研, 汤家凤2023考研高数辅导书, 2023考研高数汤家凤
<==        Row: -1986453503, 考研, 汤家凤2023考研高数辅导书, 2023考研高数汤家凤
<==        Row: -304508927, 考研, 汤家凤2023考研高数辅导书, 2023考研高数汤家凤
<==        Row: 1, 科技, Java编程思想, Java学习教程
<==        Row: 2, 科技, C++ primer plus, C++学习教程
<==        Row: 3, 人文, 阿甘正传, 在工作中学习
<==        Row: 4, 考研, 张宇高数18讲, 考研高数复习资料----张宇
<==        Row: 5, 考研, 句句真研, 田静考研英语
<==        Row: 739889167, 考研, 汤家凤2023考研高数辅导书, 2023考研高数汤家凤
<==        Row: 739889168, 考研, 汤家凤2023考研高数辅导书, 2023考研高数汤家凤
<==        Row: 739889169, 考研, 汤家凤2023考研高数辅导书, 2023考研高数汤家凤
<==      Total: 11
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@4ace284d]

对应的条件可以在官网查询:

https://baomidou.com/pages/10c804/#abstractwrapper

七、业务层快速开发

1.服务层接口继承IService<要操作的实体类>

2.接口实现类继承ServiceImpl<数据层接口, 要操作的实体类>

3.除了MyBatisPlus提供的方法接口,要自定义方法的话直接在接口中写,在实现类中实现即可

业务层接口:
public interface IBookService extends IService<Book> {
    /*
    自定义的方法
     */
    Boolean saveBook(Book book);
    Boolean modify(Book book);
    Boolean deleteById(Integer id);
}
业务层实现类
@Service
public class IBookServerImpl extends ServiceImpl<BookMapper, Book> implements IBookService {
    //自定义方法的实现
    @Autowired
    private BookMapper bookMapper;
    @Override
    public Boolean saveBook(Book book) {
        return bookMapper.insert(book)>0;
    }

    @Override
    public Boolean modify(Book book) {
        return bookMapper.updateById(book)>0;
    }

    @Override
    public Boolean deleteById(Integer id) {
        return bookMapper.deleteById(id)>0;
    }
}
数据层接口及实现
@Mapper
public interface BookMapper extends BaseMapper<Book> {

}
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_46353366/article/details/124463176

SpringBoot集成MyBatis-Plus框架详细方法-爱代码爱编程

1.说明 本文详细介绍Spring Boot集成MyBatis-Plus框架的方法, 使用MySQL数据库进行测试, 包括完整的开发到测试步骤, 从一开始的Spring Boot工程创建, 到MySQL数据库刷库脚本, 到引入mybatis-plus依赖, 然后编写实现代码和配置文件, 最后使用Junit5成功进行测试。 2.创建Spring Bo