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

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

增删改查

目录结构
image.png

1、导入依赖

<!--导入mybatisplus依赖-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.1</version>
        </dependency>

<!--mysql-->
<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>

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<UserEntity> {

}

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<UserEntity> {

}

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

serviceImpl

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

}

contronller
package com.walker.mybatisplus.controller;

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

mapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.walker.mybatisplus.mapper.UserMapper">

</mapper>

当然,每次这样子自己编写肯定是很麻烦的了,特别是表比较多的时候,所以还是要使用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<UserEntity> userEntityQueryWrapper = new QueryWrapper<>();
        userEntityQueryWrapper.eq("username","walker");
        UserEntity one = userService.getOne(userEntityQueryWrapper);
        System.out.println(one);

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

    }

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

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


        List<UserEntity> userEntities = userService.list(new LambdaQueryWrapper<UserEntity>()
                .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 {

    /**
     * 新的分页插件,一缓和二缓遵循mybatis的规则,
     * 需要设置 MybatisConfiguration#useDeprecatedExecutor = false
     * 避免缓存出现问题(该属性会在旧插件移除后一同移除)
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }


}

2、测试代码

 /**
    * 分页
    */
    @Test
    public void testPage(){

        /**
        *  方式一:使用wrapper和page进行分页查询
       */
        Page<UserEntity> page = new Page<>();
        page.setCurrent(1);
        page.setSize(1);
        QueryWrapper<UserEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("name","xiaoming");

        Page<UserEntity> userEntityPage = userService.page(page, wrapper);
        System.out.println(userEntityPage);
        
        
         /**
        * 方式二:使用mapper.xml进行编写
        */
        Page<UserEntity> mapperPage = userMapper.pageByName(page, "xiaoming");
        System.out.println(mapperPage);
    }

方式二的其他代码:
Mapper类

@Mapper
public interface UserMapper extends BaseMapper<UserEntity> {

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

xml文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.walker.mybatisplus.mapper.UserMapper">
  
  <select id="pageByName" resultType="com.walker.mybatisplus.entity.UserEntity">
    select * from user
    where name=#{name}
  </select>
</mapper>

返回结果:
image.png
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<UserEntity> 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<UserEntity> 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<UserEntity>()
                .eq(UserEntity::getUsername, "walker")
                .set(UserEntity::getPassword, "aa"));
        System.out.println(update1);


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

        /**
        * 新增或者修改
         * 这个方法的原理是:首先根据id去查询库中是否有数据,如果有的话,则进行修改
         * 如果没有的话,则进行新增
        */
        UserEntity userEntity = new UserEntity();
        userEntity.setId("1111");
        userEntity.setUsername("wwww");
        userEntity.setPassword("bbbbbbbbbb");
        userService.saveOrUpdate(userEntity);



        /**
        * 批量新增或修改,原理差不多,只是多了个数组而已
         * 也是先根据id去进行查询
        */
        ArrayList<UserEntity> 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<UserEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("username","aaaaaaaa0");
        userService.remove(wrapper);

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

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

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

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

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

    }

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Spring Boot 3.3版本尚未发布,目前最新的Spring Boot稳定版是2.7.x系列。不过,我可以为你介绍如何在较新的Spring Boot版本(如2.6.x或更高)中整合MyBatisPlus。 **整合步骤:** 1. **添加依赖**: 在你的`pom.xml`或`build.gradle`文件中,添加MyBatisPlus和Spring Data JPA的依赖。例如: Maven: ```xml <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.2</version> <!-- 最新版本号,请根据实际情况更新 --> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> ``` Gradle: ```groovy implementation 'com.baomidou:mybatis-plus-boot-starter:3.4.2' // 最新版本号,请根据实际情况更新 implementation 'org.springframework.boot:spring-boot-starter-data-jpa' ``` 2. **配置数据源**: 在`application.properties`或`application.yml`中设置数据源相关配置,比如数据库URL、用户名、密码等。 ```properties spring.datasource.url=jdbc:mysql://localhost:3306/mydb?useSSL=false spring.datasource.username=root spring.datasource.password=root spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver ``` 3. **启用扫描**: 在Spring Boot的配置类上添加`@EnableGlobalMethodSecurity`和`@EnableJpaRepositories`注解,启用全局方法安全和JPA仓库扫描。 ```java @SpringBootApplication @EnableGlobalMethodSecurity(prePostEnabled = true) @EnableJpaRepositories(basePackages = "your.package.name") public class Application { // ... } ``` 4. **实体和映射器**: 创建你的数据模型(Entity)和Mapper接口(Mapper Interface),MyBatisPlus会自动为这些接口生成对应的实现类。 5. **扫描配置**: 配置MyBatisPlus的扫描路径,通常放在启动类中: ```java @MapperScan("your.package.name.mapper") // 替换为你的Mapper接口所在的包名 ``` 6. **使用Repository**: 创建Repository接口,Spring Data JPA会自动代理这些接口并提供CRUD操作。 ```java public interface UserRepository extends JpaRepository<User, Long> { //... } ``` **相关问题--:** 1. Spring Boot 3.3的主要特性有哪些? 2. MyBatisPlus与MyBatis相比有何优势? 3. 如何处理Spring Boot中的事务管理? 4. 我需要为MyBatisPlus自定义SQL查询时怎么做?

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

WalkerShen

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值