MyBatis-Plus增删改查(基于Mapper/Service接口CRUD)

导入说明

新建一个空项目,将本项目导入空项目下

基于Mapper接口CRUD

通用 CRUD 封装BaseMapper (opens new window)接口, Mybatis-Plus 启动时自动解析实体表关系映射转换为 Mybatis 内部对象注入容器! 内部包含常见的单表操作!

实现测试案例

  1. 创建项目,导入依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.0.5</version>
    </parent>
    <groupId>com.example</groupId>
    <artifactId>curd-mapper</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <!-- 测试环境 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>

        <!-- mybatis-plus  -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.3.1</version>
        </dependency>

        <!-- 数据库相关配置启动器 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

        <!-- druid启动器的依赖  -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-3-starter</artifactId>
            <version>1.2.20</version>
        </dependency>

        <!-- 驱动类-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.28</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.28</version>
        </dependency>

    </dependencies>


    <!--    SpringBoot应用打包插件-->
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>
  1. 实体类pojo
@TableName(value ="user")
@Data
public class User implements Serializable {
   private Long id;

   private String name;

   private Integer age;

   private String email;

   private static final long serialVersionUID = 1L;
}
  1. 创建接口并继承BaseMapper

  2. 配置SpringBoot

# 连接池配置
spring:
 datasource:
   type: com.alibaba.druid.pool.DruidDataSource
   druid:
     url: jdbc:mysql://localhost:3306/mybatis-example
     username: root
     password: 123456
     driver-class-name: com.mysql.cj.jdbc.Driver

mybatis-plus:
 configuration:
   log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 控制台输出sql语句
  1. 创建测试类
@SpringBootTest(classes = MainApplication.class)
public class Mytest {
   @Autowired
   private UserMapper userMapper;

   @Test
   public void test_insert(){
       User user = new User();
       user.setAge(18);
       user.setName("aimiliya");
       user.setEmail("xxxx.email");
       //baseMapper提供的数据库插入方法
       int row = userMapper.insert(user);
   }

   @Test
   public void test_delete(){

       //根据id删除
       int rows =  userMapper.deleteById(1687124343556005889L);
       System.out.println("rows = " + rows);
       //根据age = 20
       Map param = new HashMap();
       param.put("age",20); // age = 20  and name = xx
       int i = userMapper.deleteByMap(param);
       System.out.println("i = " + i);

       //wrapper 条件封装对象,无限的封装条件
       //userMapper.delete(wrapper);
   }


   @Test
   public void  test_update(){

       //TODO: update 当属性值为null的时候,不修改!

       //updatebyId 实体类id必须有值
       //user id = 1 age改为30
       User user = new User();
       user.setId(1L);
       user.setAge(30);
       // update user set age = 30 where id = 1
       int i = userMapper.updateById(user);
       System.out.println("i = " + i);

       //将所有人的年龄改为22
       //update 实体类可以没有id值
       User user1 = new User();
       user1.setAge(22);
       int rows = userMapper.update(user,null); //null没条件
       System.out.println("rows = " + rows);
   }


   @Test
   public void test_select(){

       User user = userMapper.selectById(1);
       System.out.println("user = " + user);

       //ids集合查询
       List<Long> ids = new ArrayList<>();
       ids.add(1L); ids.add(2L);
       List<User> users = userMapper.selectBatchIds(ids);
       System.out.println("users = " + users);
   }
}

自定义和多表映射

mybatis-plus的默认mapperxml位置

mybatis-plus: # mybatis-plus的配置
  # 默认位置 private String[] mapperLocations = new String[]{"classpath*:/mapper/**/*.xml"};    
  mapper-locations: classpath:/mapper/*.xml

自定义mapper方法:

public interface UserMapper extends BaseMapper<User> {

    //正常自定义方法!
    //可以使用注解@Select或者mapper.xml实现
    List<User> queryAll();
}

基于mapper.xml实现:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- namespace = 接口的全限定符 -->
<mapper namespace="com.example.mapper.UserMapper">

   <select id="queryAll" resultType="user" >
       select * from user
   </select>
</mapper>

基于Service接口CRUD

对比Mapper接口CRUD区别:

  • service添加了批量方法
  • service层的方法自动添加事务

使用Iservice接口方式

接口继承IService接口

public interface UserService extends IService<User> {
}

类继承ServiceImpl实现类

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService{

}

测试:

@SpringBootTest(classes = MainApplication.class)
public class MyBatisPlusTest {

    @Autowired
    private UserService userService;

    @Test
    public void  test_save(){

        List<User> list = new ArrayList<>();
        User user = new User();
        user.setAge(18);
        user.setEmail("xx.email.com");
        user.setName("艾米莉亚");
        list.add(user);

        User user1 = new User();
        user1.setAge(18);
        user1.setEmail("jj.e");
        user1.setName("486");
        list.add(user1);

        boolean b = userService.saveBatch(list);
        System.out.println("b = " + b);

    }

    @Test
    public void  test_saveOrUpdate(){

        //如果有id有值 不为null,修改  为null插入
        User user = new User();
        user.setId(1L);
        user.setAge(18);
        user.setEmail("jj");
        user.setName("拉姆");
        userService.saveOrUpdate(user);

    }
    @Test
    public void  test_remove(){

        boolean b = userService.removeById(1687120798123302914L);
        System.out.println("b = " + b);
    }
    @Test
    public void  test_update(){

        User user = new User();
        user.setId(1L);
        user.setAge(18);
        user.setEmail("jj");
        user.setName("蕾姆");
        userService.updateById(user);

    }

    @Test
    public void  test_getOrList(){

        User byId = userService.getById(1L);//get返回的是单个对象
        System.out.println("byId = " + byId);
        List<User> list = userService.list(null);//查询全部,返回的集合
        System.out.println("list = " + list);

    }
}

CRUD方法介绍

保存:
// 插入一条记录(选择字段,策略插入)
boolean save(T entity);
// 插入(批量)
boolean saveBatch(Collection<T> entityList);
// 插入(批量),batchSize表示每批次保存的实体数量。通过指定批量大小,可以控制一次提交的实体数量
boolean saveBatch(Collection<T> entityList, int batchSize);

修改或者保存:
// TableId 注解存在更新记录,否插入一条记录
boolean saveOrUpdate(T entity);
// 根据updateWrapper尝试更新,否继续执行saveOrUpdate(T)方法
boolean saveOrUpdate(T entity, Wrapper<T> updateWrapper);
// 批量修改插入
boolean saveOrUpdateBatch(Collection<T> entityList);
// 批量修改插入
boolean saveOrUpdateBatch(Collection<T> entityList, int batchSize);

移除:
// 根据 queryWrapper 设置的条件,删除记录
boolean remove(Wrapper<T> queryWrapper);
// 根据 ID 删除
boolean removeById(Serializable id);
// 根据 columnMap 条件,删除记录
boolean removeByMap(Map<String, Object> columnMap);
// 删除(根据ID 批量删除)
boolean removeByIds(Collection<? extends Serializable> idList);

更新:
// 根据 UpdateWrapper 条件,更新记录 需要设置sqlset
boolean update(Wrapper<T> updateWrapper);
// 根据 whereWrapper 条件,更新记录
boolean update(T updateEntity, Wrapper<T> whereWrapper);
// 根据 ID 选择修改
boolean updateById(T entity);
// 根据ID 批量更新
boolean updateBatchById(Collection<T> entityList);
// 根据ID 批量更新
boolean updateBatchById(Collection<T> entityList, int batchSize);

数量: 
// 查询总记录数
int count();
// 根据 Wrapper 条件,查询总记录数
int count(Wrapper<T> queryWrapper);

查询:
// 根据 ID 查询
T getById(Serializable id);
// 根据 Wrapper,查询一条记录。结果集,如果是多个会抛出异常,随机取一条加上限制条件 wrapper.last("LIMIT 1")
T getOne(Wrapper<T> queryWrapper);
// 根据 Wrapper,查询一条记录
T getOne(Wrapper<T> queryWrapper, boolean throwEx);
// 根据 Wrapper,查询一条记录
Map<String, Object> getMap(Wrapper<T> queryWrapper);
// 根据 Wrapper,查询一条记录
<V> V getObj(Wrapper<T> queryWrapper, Function<? super Object, V> mapper);

集合:
// 查询所有
List<T> list();
// 查询列表
List<T> list(Wrapper<T> queryWrapper);
// 查询(根据ID 批量查询)
Collection<T> listByIds(Collection<? extends Serializable> idList);
// 查询(根据 columnMap 条件)
Collection<T> listByMap(Map<String, Object> columnMap);
// 查询所有列表
List<Map<String, Object>> listMaps();
// 查询列表
List<Map<String, Object>> listMaps(Wrapper<T> queryWrapper);
// 查询全部记录
List<Object> listObjs();
// 查询全部记录
<V> List<V> listObjs(Function<? super Object, V> mapper);
// 根据 Wrapper 条件,查询全部记录
List<Object> listObjs(Wrapper<T> queryWrapper);
// 根据 Wrapper 条件,查询全部记录
<V> List<V> listObjs(Wrapper<T> queryWrapper, Function<? super Object, V> mapper);

  • 9
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值