SpringBoot整合Mybatisplus3.x之CRUD

Posted 天宇轩-王

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringBoot整合Mybatisplus3.x之CRUD相关的知识,希望对你有一定的参考价值。

  • pom.xml

     1 <dependencies>
     2         <dependency>
     3             <groupId>org.springframework.boot</groupId>
     4             <artifactId>spring-boot-starter</artifactId>
     5         </dependency>
     6         <dependency>
     7             <groupId>org.springframework.boot</groupId>
     8             <artifactId>spring-boot-starter-test</artifactId>
     9             <scope>test</scope>
    10         </dependency>
    11         <dependency>
    12             <groupId>org.projectlombok</groupId>
    13             <artifactId>lombok</artifactId>
    14             <optional>true</optional>
    15         </dependency>
    16         <dependency>
    17             <groupId>com.baomidou</groupId>
    18             <artifactId>mybatis-plus-boot-starter</artifactId>
    19             <version>3.2.0</version>
    20         </dependency>
    21         <dependency>
    22             <groupId>com.h2database</groupId>
    23             <artifactId>h2</artifactId>
    24             <scope>runtime</scope>
    25         </dependency>
    26         <dependency>
    27             <groupId>p6spy</groupId>
    28             <artifactId>p6spy</artifactId>
    29         </dependency>
    30     </dependencies>
    31 ?
    32     <build>
    33         <plugins>
    34             <plugin>
    35                 <groupId>org.springframework.boot</groupId>
    36                 <artifactId>spring-boot-maven-plugin</artifactId>
    37             </plugin>
    38         </plugins>
    39     </build>

     

  • application.yml

    # DataSource Config
    spring:
      datasource:
        driver-class-name: org.h2.Driver
        url: jdbc:h2:tcp://192.168.180.115:19200/~/mem/test
        username: root
        password: test
    ?
    # Logger Config
    logging:
      level:
        com.mp.crud: debug
    ?
  • dao层

    public interface UserMapper extends BaseMapper<User> {
    ?
    }

     

  • 实体类

     1 @Data
     2 @Accessors(chain = true)
     3 @TableName("user")
     4 public class User {
     5 ?
     6     private Long id;
     7     private String name;
     8     private Integer age;
     9     private String email;
    10 ?
    11     @TableField(exist = false)
    12     private Integer count;
    13 }
    ?
  • 配置类

    1 @Configuration
    2 @MapperScan("com.mp.crud.mapper")
    3 public class MybatisPlusConfig {
    4 ?
    5 }
    6 ?

     

  • 测试类

      1 @SpringBootTest
      2 @RunWith(SpringRunner.class)
      3 class CrudApplicationTests {
      4 ?
      5     @Resource
      6     private UserMapper mapper;
      7 ?
      8     @Test
      9     public void aInsert() {
     10         User user = new User();
     11         user.setName("小羊");
     12         user.setAge(3);
     13         user.setEmail("abc@mp.com");
     14         assertThat(mapper.insert(user)).isGreaterThan(0);
     15         // 成功直接拿会写的 ID
     16         assertThat(user.getId()).isNotNull();
     17     }
     18 ?
     19 ?
     20     @Test
     21     public void bDelete() {
     22         assertThat(mapper.deleteById(3L)).isGreaterThan(0);
     23         assertThat(mapper.delete(new QueryWrapper<User>()
     24                 .lambda().eq(User::getName, "Sandy"))).isGreaterThan(0);
     25     }
     26 ?
     27 ?
     28     @Test
     29     public void cUpdate() {
     30         //UPDATE user SET email=? WHERE id=?
     31         assertThat(mapper.updateById(new User().setId(1L).setEmail("ab@c.c"))).isGreaterThan(0);
     32         //UPDATE user SET name=?, age=? WHERE (id = ?)
     33         assertThat(
     34                 mapper.update(
     35                         new User().setName("mp"),
     36                         Wrappers.<User>lambdaUpdate()
     37                                 .set(User::getAge, 3)
     38                                 .eq(User::getId, 2)
     39                 )
     40         ).isGreaterThan(0);
     41         User user = mapper.selectById(2);
     42         assertThat(user.getAge()).isEqualTo(3);
     43         assertThat(user.getName()).isEqualTo("mp");
     44 ?
     45         mapper.update(
     46                 null,
     47                 Wrappers.<User>lambdaUpdate().set(User::getEmail, null).eq(User::getId, 2)
     48         );
     49         assertThat(mapper.selectById(1).getEmail()).isEqualTo("ab@c.c");
     50         user = mapper.selectById(2);
     51         assertThat(user.getEmail()).isNull();
     52         assertThat(user.getName()).isEqualTo("mp");
     53 ?
     54         mapper.update(
     55                 new User().setEmail("miemie@baomidou.com"),
     56                 new QueryWrapper<User>()
     57                         .lambda().eq(User::getId, 2)
     58         );
     59         user = mapper.selectById(2);
     60         assertThat(user.getEmail()).isEqualTo("miemie@baomidou.com");
     61 ?
     62         mapper.update(
     63                 new User().setEmail("miemie2@baomidou.com"),
     64                 Wrappers.<User>lambdaUpdate()
     65                         .set(User::getAge, null)
     66                         .eq(User::getId, 2)
     67         );
     68         user = mapper.selectById(2);
     69         assertThat(user.getEmail()).isEqualTo("miemie2@baomidou.com");
     70         assertThat(user.getAge()).isNull();
     71     }
     72 ?
     73 ?
     74     @Test
     75     public void dSelect() {
     76         mapper.insert(
     77                 new User().setId(10086L)
     78                         .setName("miemie")
     79                         .setEmail("miemie@baomidou.com")
     80                         .setAge(3));
     81         assertThat(mapper.selectById(10086L).getEmail()).isEqualTo("miemie@baomidou.com");
     82         User user = mapper.selectOne(new QueryWrapper<User>().lambda().eq(User::getId, 10086));
     83         assertThat(user.getName()).isEqualTo("miemie");
     84         assertThat(user.getAge()).isEqualTo(3);
     85 ?
     86         List<User> users = mapper.selectList(Wrappers.<User>lambdaQuery().select(User::getId));
     87         System.out.println(users);
     88 ?
     89         mapper.selectList(Wrappers.<User>lambdaQuery().select(User::getId))
     90                 .forEach(x -> {
     91                     assertThat(x.getId()).isNotNull();
     92                     assertThat(x.getEmail()).isNull();
     93                     assertThat(x.getName()).isNull();
     94                     assertThat(x.getAge()).isNull();
     95                 });
     96         mapper.selectList(new QueryWrapper<User>().select("id", "name"))
     97                 .forEach(x -> {
     98                     assertThat(x.getId()).isNotNull();
     99                     assertThat(x.getEmail()).isNull();
    100                     assertThat(x.getName()).isNotNull();
    101                     assertThat(x.getAge()).isNull();
    102                 });
    103     }
    104 ?
    105     @Test
    106     public void orderBy() {
    107         List<User> users = mapper.selectList(Wrappers.<User>query().orderByAsc("age"));
    108         System.out.println(users);
    109         //assertThat(users).isNotEmpty();
    110     }
    111 ?
    112     @Test
    113     public void selectMaps() {
    114         List<Map<String, Object>> mapList = mapper.selectMaps(Wrappers.<User>query().orderByAsc("age"));
    115         assertThat(mapList).isNotEmpty();
    116         assertThat(mapList.get(0)).isNotEmpty();
    117         //{ID=1189005852158324737, EMAIL=abc@mp.com, NAME=小羊, AGE=3}
    118         System.out.println(mapList.get(0));
    119     }
    120 ?
    121     @Test
    122     public void selectMapsPage() {
    123         IPage<Map<String, Object>> page = mapper.selectMapsPage(new Page<>(1, 5), Wrappers.<User>query().orderByAsc("age"));
    124         assertThat(page).isNotNull();
    125         assertThat(page.getRecords()).isNotEmpty();
    126         assertThat(page.getRecords().get(0)).isNotEmpty();
    127     }
    128 ?
    129     @Test
    130     public void orderByLambda() {
    131         //SELECT id,name,email,age FROM user ORDER BY age ASC
    132         List<User> users = mapper.selectList(Wrappers.<User>lambdaQuery().orderByAsc(User::getAge));
    133         List<User>  users1 = mapper.selectList(Wrappers.<User>query().orderByAsc("age"));
    134         System.out.println(users1);
    135         //assertThat(users).isNotEmpty();
    136     }
    137 ?
    138     @Test
    139     public void testSelectMaxId() {
    140         // SELECT max(id) as id FROM user
    141         QueryWrapper<User> wrapper = new QueryWrapper<>();
    142         wrapper.select("max(id) as id");
    143         //User(id=1189005852158324737, name=null, age=null, email=null, count=null)
    144         User user = mapper.selectOne(wrapper);
    145         System.out.println(user);
    146         System.out.println("maxId=" + user.getId());
    147         List<User> users = mapper.selectList(Wrappers.<User>lambdaQuery().orderByDesc(User::getId));
    148         Assert.assertEquals(user.getId().longValue(), users.get(0).getId().longValue());
    149     }
    150 ?
    151     @Test
    152     public void testGroup() {
    153         QueryWrapper<User> wrapper = new QueryWrapper<>();
    154         wrapper.select("age, count(*)")
    155                 .groupBy("age");
    156         List<Map<String, Object>> maplist = mapper.selectMaps(wrapper);
    157         for (Map<String, Object> mp : maplist) {
    158             System.out.println(mp);
    159         }
    160         /**
    161          * lambdaQueryWrapper groupBy orderBy
    162          */
    163         LambdaQueryWrapper<User> lambdaQueryWrapper = new QueryWrapper<User>().lambda()
    164                 .select(User::getAge)
    165                 .groupBy(User::getAge)
    166                 .orderByAsc(User::getAge);
    167         for (User user : mapper.selectList(lambdaQueryWrapper)) {
    168             System.out.println(user);
    169         }
    170     }
    171 ?
    172     @Test
    173     public void testTableFieldExistFalse(){
    174         QueryWrapper<User> wrapper = new QueryWrapper<>();
    175         wrapper.select("age, count(age) as count")
    176                 .groupBy("age");
    177         List<User> list = mapper.selectList(wrapper);
    178         list.forEach(System.out::println);
    179         list.forEach(x->{
    180             Assert.assertNull(x.getId());
    181             Assert.assertNotNull(x.getAge());
    182             Assert.assertNotNull(x.getCount());
    183         });
    184         mapper.insert(
    185                 new User().setId(10088L)
    186                         .setName("miemie")
    187                         .setEmail("miemie@baomidou.com")
    188                         .setAge(3));
    189         User miemie = mapper.selectById(10088L);
    190         Assert.assertNotNull(miemie);
    191 ?
    192     }
    193 ?
    194 }
    195 ?

     

  • 测试结果(我处只运行了部分的测试方法)

     

以上是关于SpringBoot整合Mybatisplus3.x之CRUD的主要内容,如果未能解决你的问题,请参考以下文章

SpringBoot整合MybatisPlus3.X之自定义Mapper

SpringBoot整合MybatisPlus3.X之SQL执行分析插件(十四)

springboot-mybatisplus笔记

Vue+SpringBoot超详细!一周开发一个SpringBoot + Vue+MybatisPlus+Shiro+JWT+Redis前后端分离个人博客项目!!!项目完结

Vue+SpringBoot超详细!一周开发一个SpringBoot + Vue+MybatisPlus+Shiro+JWT+Redis前后端分离个人博客项目!!!项目完结

阿昌教你看懂mybatisplus的sql语句的创建过程