<thead id="rrjt3"></thead>
      <progress id="rrjt3"><dfn id="rrjt3"></dfn></progress>

      <em id="rrjt3"></em>

        <address id="rrjt3"><ins id="rrjt3"><dfn id="rrjt3"></dfn></ins></address>
          <i id="rrjt3"></i>

        SpringBoot整合mybatis-plus入門教程

        時間:2022-10-07 10:19:55 類型:JAVA
        字號:    

        Mybatis-plus的介紹及優缺點,這里不再詳細說明,需要的朋友到官網支詳細了解

        下面就用一個springboot項目mybatis-plus 的基礎操作

        第一步:數據庫準備

        CREATE TABLE `data0917`.`student`  (
          `id` int(11) NOT NULL AUTO_INCREMENT,
          `name` varchar(30) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
          `sex` char(1) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '男',
          `blood` varchar(2) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '血型',
          PRIMARY KEY (`id`) USING BTREE
        ) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

        第二步:核心依賴

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.1</version>
        </dependency>
        
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

          這些是核心依賴,用到了mysql驅動、lombok。集成mybatis-plus要把mybatis、mybatis-spring去掉,避免沖突;lombok是一個工具,添加了這個依賴,就可以使用它的簡化功能,最常用的用法就是在實體類中使用它的@Data注解,這樣實體類就不用寫set、get、toString等方法了。

        第三步:application.yml配置

        mybatis-plus:
          configuration:
            log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
            #開啟sql日志
            map-underscore-to-camel-case: true
            # 該配置就是將帶有下劃線的表字段映射為駝峰格式的實體類屬性
        spring:
          datasource:
            driver-class-name: com.mysql.cj.jdbc.Driver
            url: jdbc:mysql://localhost:3306/data0917?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=UTF-8
            username: root
            password: root

        第四步:實體類Student.java

        import com.baomidou.mybatisplus.annotation.IdType;
        import com.baomidou.mybatisplus.annotation.TableId;
        import lombok.Data;
        
        @Data
        public class Student {
            @TableId(value = "id", type = IdType.AUTO)//指定自增策略
            private Integer id;
            private String name;
            private String sex;
            private String blood;
        }

        第五步:StudentMapper.java

        import com.baomidou.mybatisplus.core.mapper.BaseMapper;
        import com.example.springbootmybatisplus.entity.Student;
        import org.apache.ibatis.annotations.Mapper;
        
        @Mapper
        //表明這是一個Mapper,也可以在啟動類上加上包掃描
        //Mapper 繼承該接口后,無需編寫 mapper.xml 文件,即可獲得CRUD功能
        public interface StudentMapper  extends BaseMapper<Student> {
        }

          這樣就完成了mybatis-plus與springboot的整合。把mybatis和mybatis-spring依賴換成mybatis-plus的依賴,最后mapper繼承BaseMapper即可。

        第六步:Mybatis分頁插件配置

        import com.baomidou.mybatisplus.annotation.DbType;
        import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
        import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
        import org.springframework.context.annotation.Bean;
        import org.springframework.context.annotation.Configuration;
        
        @Configuration
        public class MyBatisPlusPager {
            /**
             * 分頁插件
             *
             * @return 分頁插件的實例
             */
            @Bean
            public MybatisPlusInterceptor mybatisPlusInterceptor() {
                MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
                //指定數據庫類型是 MySQL
                interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
                return interceptor;
            }
        }

        第七步:StudentService.java

        import com.example.springbootmybatisplus.entity.Student;
        import com.example.springbootmybatisplus.mapper.StudentMapper;
        import org.springframework.beans.factory.annotation.Autowired;
        import org.springframework.stereotype.Service;
        
        import java.util.List;
        
        @Service
        public class StudentService {
            @Autowired
            private StudentMapper studentMapper;
            //查詢全部
            public List<Student> selectAll() {
                return studentMapper.selectList(null);
            }
        
            //添加一條數據
            public int add(Student student) {
                return studentMapper.insert(student);
            }
        
            public Student queryById(Student student) {
                return studentMapper.selectById(student.getId());
            }
            //多條件判斷判斷查詢 及 分頁
                //當姓名,性別,血型不為空時, 進行條件查詢
                public Page<Student> queryWhere(Student student,Page studentPage){
                    QueryWrapper<Student> wrapper = new QueryWrapper<>();
                    wrapper.like("".equals(student.getName()) == false && student.getName() != null, "name",student.getName())
                            .eq("".equals(student.getSex()) == false && student.getSex() != null, "sex",student.getSex())
                            .eq("".equals(student.getBlood()) == false && student.getBlood() != null, "blood",student.getBlood());
                    return studentMapper.selectPage(studentPage,wrapper);
                }
        }

        第八步:測試類

        import com.example.springbootmybatisplus.entity.Student;
        import com.example.springbootmybatisplus.service.StudentService;
        import org.junit.jupiter.api.Test;
        import org.springframework.beans.factory.annotation.Autowired;
        import org.springframework.boot.test.context.SpringBootTest;
        
        @SpringBootTest
        public class StudentCURDTest {
            @Autowired
            private StudentService studentService;
        
            @Test
            public void queryAll() {
                studentService.selectAll().forEach(System.out::println);
            }
        
            @Test
            public void addOne(){
                Student student = new Student();
                student.setName("小小雨");
                student.setSex("男");
                student.setBlood("A");
                System.out.println(studentService.add(student));
            }
            @Test void queryOne(){
                Student student = new Student();
                student.setId(1);
                System.out.println(studentService.queryById(student));
            }
            @Test void queryWhere(){
                    Page<Student> studentPage = new Page<Student>(1L, 2L);
                    Student student = new Student();
                    student.setName("小");
                    //student.setBlood("A");
                    Page<Student> studentPage1 =studentService.queryWhere(student,studentPage);
                    System.out.println("pages"+ studentPage1.getPages());
                    System.out.println("total:"+studentPage1.getTotal());
                    System.out.println("size:"+studentPage1.getSize());
                    studentPage1.getRecords().forEach(System.out::println);
                }
        }

        Mybatis-plus之IService的使用(以上面的內容為基礎), 簡單列具兩個實例

        第一步:創建StuService.java接口, 繼承IService

        import com.baomidou.mybatisplus.extension.service.IService;
        import com.example.springbootmybatisplus.entity.Student;
        
        public interface StuService extends IService<Student> {
        }

        第二步: 定義實現類StuServiceImpl.java

        import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
        import com.example.springbootmybatisplus.entity.Student;
        import com.example.springbootmybatisplus.mapper.StudentMapper;
        import org.springframework.stereotype.Service;
        
        @Service
        public class StuServiceImpl extends ServiceImpl<StudentMapper, Student> implements StuService{
        }

        第三步:測試調用

        @Test void iServiceSaveTest(){
            Student student = new Student();
            student.setName("小小雨");
            student.setSex("男");
            student.setBlood("A");
            System.out.println(stuService.save(student));
        }
        
        //IPage分頁及多條件查詢
        @Test void iServiceIPageTest(){
            IPage<Student> studentPage = new Page<>(1l,2l);
        
            Student student = new Student();
            student.setName("小小雨");
            student.setSex("男");
            student.setBlood("A");
            
            QueryWrapper<Student> wrapper = new QueryWrapper<>();
            wrapper.like("".equals(student.getName()) == false && student.getName() != null, "name",student.getName())
                    .eq("".equals(student.getSex()) == false && student.getSex() != null, "sex",student.getSex())
                    .eq("".equals(student.getBlood()) == false && student.getBlood() != null, "blood",student.getBlood());
        
            IPage<Student> studentPage1 =stuService.page(studentPage,wrapper);
            System.out.println("pages"+ studentPage1.getPages());
            System.out.println("total:"+studentPage1.getTotal());
            System.out.println("size:"+studentPage1.getSize());
            studentPage1.getRecords().forEach(System.out::println);
        }


        黄网站免费 <