栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

【springboot系列】springboot整合mybatisplus实现CRUD

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【springboot系列】springboot整合mybatisplus实现CRUD

大家好,我是程序员walker
一个持续学习,分享干货的博主
关注公众号【I am Walker】,一块进步

增删改查

目录结构

1、导入依赖

        
            com.baomidou
            mybatis-plus-boot-starter
            3.5.1
        



            mysql
            mysql-connector-java
            runtime
        

        
            org.projectlombok
            lombok
            true
        
2、配置参数

在applicatoin.yml中配置参数

spring:
# 数据库配置
  datasource:
    url: jdbc:mysql://localhost/test?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimeZone=UTC
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver

# mybatisplus配置
mybatis-plus:
  # 配置xml路径
  mapper-locations: classpath*:/mapper*.xml

3、启动类配置

配置@MapperScan,这一步的目的,主要是扫描到Mapper类

package com.walker.mybatisplus;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
//配置mapperscan 扫描mapper下的类
@MapperScan("com.walker.mybatisplus.mapper")
public class SpringbootMybatisplusApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootMybatisplusApplication.class, args);
    }

}

4、代码编写

代码主要有以下几类

  • entity:数据库实体类
  • mapper:mapper类
  • service
  • serviceImpl
  • controller

下面便以表user为案例,编写对应的类
数据表结构

CREATE TABLE `user` (
  `id` varchar(64) NOT NULL,
  `username` varchar(64) DEFAULT NULL,
  `password` varchar(64) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3;
entity
package com.walker.mybatisplus.entity;

import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
import lombok.Getter;
import lombok.Setter;

//@Data是lombok的注解,用于自动生成setter和getter方法
@Data
@TableName("user") //对应数据库的表名
//Serializable:代表这个类可进行序列化
public class UserEntity implements Serializable {

    private static final long serialVersionUID = 1L;

    private String id;

    private String username;

    private String password;
    
    private String name;
}

mapper
package com.walker.mybatisplus.mapper;

import com.walker.mybatisplus.entity.UserEntity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;

//继承BaseMapper类,这个类是mybatisplus自己封装的,内部
@Mapper
public interface UserMapper extends BaseMapper {

}

service
package com.walker.mybatisplus.service;

import com.walker.mybatisplus.entity.UserEntity;
import com.baomidou.mybatisplus.extension.service.IService;

//接口类,继承IService
public interface UserService extends IService {

}

Iservice方法是mybatisplus自己整合的方法,其中有很多已经整理好的增删改查方法,不需要自己再去重新写,这也是使用mybatisplus的方便之处

serviceImpl
@Service(value = "userService") //这里需要添加@Service注入容器
//继承ServiceImpl  其中的泛型注意一定要填写
//实现Iservice
public class UserServiceImpl extends ServiceImpl 
implements UserService {

}

contronller
package com.walker.mybatisplus.controller;

//@RestController:Json字符串的形式返回给客户端,如果不需要强制定义的话,就使用@Controller
@RestController
//请求映射,定义url
@RequestMapping("/user")
public class UserController {
    
}

mapper.xml





当然,每次这样子自己编写肯定是很麻烦的了,特别是表比较多的时候,所以还是要使用mybatisplus中的代码生成器了
官方文档:https://baomidou.com/pages/779a6e/#%E5%BF%AB%E9%80%9F%E5%85%A5%E9%97%A8

当然也可以参照我以前的文章
【springboot系列】使用mybatisplus代码生成器

5、实践

本次代码实践都在springboot的test中进行,方便快速地进行调用,基础代码如下,后面实践的代码可以自己进行补充

@SpringBootTest
public class WalkerMybatisPlusTest {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserService userService;
    
}
查询 单个查询
    
    @Test
    public void testGetOne(){
        //方式一;使用QueryWrapper 但是对于列名需要自己手动写,所以相对而言还是Lambda比较方便
        QueryWrapper userEntityQueryWrapper = new QueryWrapper<>();
        userEntityQueryWrapper.eq("username","walker");
        UserEntity one = userService.getOne(userEntityQueryWrapper);
        System.out.println(one);

        //方式二:使用lambda表达式
        UserEntity walker = userService.getOne(new LambdaQueryWrapper()
                .eq(UserEntity::getUsername, "walker"));
        System.out.println(walker);

    }

可能出现异常
1、One record is expected, but the query result is multiple records
原因:getOne查询的是单个的,如果查到数据库有多条,则会抛出异常

多个查询
    
    @Test
    public void testList(){
        QueryWrapper wrapper = new QueryWrapper<>();
        wrapper.eq("name","xiaoming");
        List list = userService.list(wrapper);
        System.out.println(list);


        List userEntities = userService.list(new LambdaQueryWrapper()
                .eq(UserEntity::getName, "xiaoming"));
        System.out.println(userEntities);
    }
分页

1、添加插件配置

package com.walker.mybatisplus.common.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MybatisPlusConfig {

    
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }


}

2、测试代码

 
    @Test
    public void testPage(){

        
        Page page = new Page<>();
        page.setCurrent(1);
        page.setSize(1);
        QueryWrapper wrapper = new QueryWrapper<>();
        wrapper.eq("name","xiaoming");

        Page userEntityPage = userService.page(page, wrapper);
        System.out.println(userEntityPage);
        
        
         
        Page mapperPage = userMapper.pageByName(page, "xiaoming");
        System.out.println(mapperPage);
    }

方式二的其他代码:
Mapper类

@Mapper
public interface UserMapper extends BaseMapper {

    Page pageByName(Page page, @Param(value = "name") String name);
}

xml文件




  
  
    select * from user
    where name=#{name}
  

返回结果:

records:记录,我们查到的数据就在这里
total:总数,就是数据库中查到的数据的总数
size:每页的长度,这个是我们自己定义的
current:当前的页数

两者都有各自的优缺点,但在实际应用中,方式二应该是比较多的,主要是他比较容易维护,查询sql存放于xml中,但是就需要一定的sql能力
而使用wrapper对于简单的sql的话,是一定帮助的,但是对于较复杂的分页查询,那么是不大推荐的

新增|修改 新增
@Test
    public void testSave(){
        //新增单个
        UserEntity userEntity = new UserEntity();
        userEntity.setUsername("BB");
        userEntity.setPassword("aa");
        userEntity.setName("xxx");
        userService.save(userEntity);


        //批量新增
        ArrayList userEntities = new ArrayList<>();
        UserEntity tempUser;
        for (int i = 0; i < 5; i++) {
            tempUser=new UserEntity();
            tempUser.setName("a"+i);
            tempUser.setUsername("b"+i);
            tempUser.setPassword("123");
            userEntities.add(tempUser);
        }
        userService.saveBatch(userEntities);

    }
修改
@Test
    public void update(){

        //单个修改
        //使用wrapper
        UpdateWrapper wrapper = new UpdateWrapper<>();
        wrapper.eq("username","walker");
        wrapper.set("password","1111111111");
        boolean update = userService.update(wrapper);
        System.out.println(update);


        //使用lambda wrapper
        boolean update1 = userService.update(new LambdaUpdateWrapper()
                .eq(UserEntity::getUsername, "walker")
                .set(UserEntity::getPassword, "aa"));
        System.out.println(update1);


        //根据id进行修改
        //这个方法会对值不为null的列进行修改
        UserEntity walker = userService.getOne(new LambdaQueryWrapper().eq(UserEntity::getUsername, "walker"));
        walker.setPassword("bbbbbbbbbbbbbbbb");
        userService.updateById(walker);
        
    }
新增或修改
@Test
    public void testSaveOrUpdate(){

        
        UserEntity userEntity = new UserEntity();
        userEntity.setId("1111");
        userEntity.setUsername("wwww");
        userEntity.setPassword("bbbbbbbbbb");
        userService.saveOrUpdate(userEntity);



        
        ArrayList userEntities = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            UserEntity userEntity1 = new UserEntity();
            userEntity1.setPassword("a");
            userEntity1.setUsername("aaaaaaaa"+i);
            userEntities.add(userEntity1);
        }
        userService.saveOrUpdateBatch(userEntities);
    }
删除
 @Test
    public void testDel(){
        //根据wrapper移除
        QueryWrapper wrapper = new QueryWrapper<>();
        wrapper.eq("username","aaaaaaaa0");
        userService.remove(wrapper);

        //根据lambdawrapper移除
        userService.remove(new LambdaQueryWrapper().eq(UserEntity::getUsername,"aaaaaaaa1"));

        //根据id移除
        userService.removeById("1111");

        //根据类的id移除
        UserEntity userEntity = new UserEntity();
        userEntity.setId("1525765938643283971");
        userService.removeById(userEntity);

        //根据id数组移除,相当于批量移除
        ArrayList ids = new ArrayList<>();
        ids.add("1526572897000767490");
        ids.add("1526572906890936322");
        userService.removeBatchByIds(ids);

        //根据map移除
        HashMap map = new HashMap<>();
        map.put("username","b4");
        userService.removeByMap(map);

    }
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/895036.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号