速通MybatisPlus

1、环境配置

1.1 application.yml

  • 加入日志功能
  • 设置实体类所对应的表的前缀
# 应用服务 WEB 访问端口
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: pj123456
    url: jdbc:mysql://localhost:3306/mybatis_plus?characterEncoding=utf-8&serverTimezone=Asia/Shanghai
  main:
    allow-circular-references: true

mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  # 设置MyBatis-Plus的全局配置
  global-config:
    db-config:
      # 设置实体类所对应的表的统一前缀
      table-prefix: t_
      # 设置统一的主键生成策略
      id-type: auto

1.2 pom.xml

<!--mybatis-plus启动器-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.1</version>
        </dependency>

        <!--lombok用于简化实体类开发-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <!--mysql驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

1.3 创建mapper以及在resoure下面创建对应的mapperxml

  • 继承basemapper并且映射对应的实体类型
  • 在启动项上添加MapperScan
@Repository
public interface UserMapper extends BaseMapper<User> {

    Map<String,Object> SelectById(Long id);
}
@SpringBootApplication
@MapperScan("com.melon.mp.mapper")
public class SpringbootMybatisplusApplication {

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

}

2、增删改查

  • 返回的类型都是int

2.1 增

  • 首先在测试文件中将UserMapper注入
@Test
public void testInsert(){
    User user = new User();
    user.setName("张三");
    user.setAge(18);
    user.setEmail("123@gmail.com");
    int result = userMapper.insert(user);
    System.out.println("result"+result);
    System.out.println("id"+user.getId());
}

2.2 删

  • 根据条件删除使用 Map类型
    public void testDelete(){
        // 根据id删除 DELETE FROM user WHERE id=?
        int result = userMapper.deleteById(1778611896094601218L);
        System.out.println("result"+ result);

        // 根据条件删除 DELETE FROM user WHERE name = ? AND age = ?
        Map<String,Object> map = new HashMap<>();
        map.put("name","张三");
        map.put("age",18);
        int result = userMapper.deleteByMap(map);
        System.out.println("result"+ result);

        // 批量删除 DELETE FROM user WHERE id IN ( ? , ? , ? )
        List<Long> list = Arrays.asList(4L, 5L, 6L);
        int result = userMapper.deleteBatchIds(list);
        System.out.println("result"+ result);
    }

2.3 改

    @Test
    // update UPDATE user SET name=?, age=? WHERE id=?
    public void testUpdate(){
        User user = new User();
        user.setId(4L);
        user.setName("李四");
        user.setAge(44);
        int result = userMapper.updateById(user);
        System.out.println("result"+ result);
    }

2.4 查

  • 批量查询使用map
    @Test
    public void testSelect(){
        // 根据id查询 SELECT id,name,age,email FROM user WHERE id=?
        User user = userMapper.selectById(1L);
        System.out.println(user);

        // 批量查询 SELECT id,name,age,email FROM user WHERE id IN ( ? , ? , ? )
        List<Long> list = Arrays.asList(1L, 2L, 3L);
        userMapper.selectBatchIds(list);
        System.out.println(list);

        // 条件查询 SELECT id,name,age,email FROM user WHERE name = ? AND age = ?
        Map<String, Object> map = new HashMap<>();
        map.put("name","Laura");
        map.put("age",26);
        List<User> users = userMapper.selectByMap(map);
        System.out.println(users);

        // 自定义查询 select id,name,age,email from user where id = ?
        Map<String, Object> map = userMapper.SelectById(1L);
        System.out.println(map);
    }

3、service接口

  1. 创建UserService接口
    • UserService需要继承IService,并且继承需要处理的实体类型IService
public interface UserService extends IService<User> {
}
  1. 创建实现类UserServiceImpl
    • 注册为组件@Service
    • 继承ServiceImpl时<UserMapper,User>第一个对应的是对应实体类的Mapper,第二个参数是处理的实体类
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
}

3.1 测试service查询总数

  • 先讲UserService注入
    @Test
    // 查询总记录数
    public void testSelect(){
        long count = userService.count();
        System.out.println(count);
    }

3.2 测试service批量添加

    @Test
    // 批量添加
    public void testInsert(){
        List<User> list = new ArrayList<>();
        for(int i=1;i<=5;i++){
            User user = new User();
            user.setName("ybc"+i);
            user.setAge(20+i);
            list.add(user);
        }
        boolean b = userService.saveBatch(list);
        System.out.println(b);
    }

4、常用注解

4.1 @TableName

// 如果实体类与数据库中的表名不一致,指定数据库中的表名
@TableName("user")
  • 也可以通过配置全局配置文件,指定去什么表中查询
  • 配置前缀t_,即默认在t_开头的表中去查询
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  # 设置MyBatis-Plus的全局配置
  global-config:
    db-config:
      # 设置实体类所对应的表的统一前缀
      table-prefix: t_
      # 设置统一的主键生成策略
      id-type: auto

4.2 @TableId

// 将属性所对应的字段定为主键
// @TableId注解的value属性用于指定主键的字段
// @TableId注解的type属性用于指定主键生成策略,确实数据库主键设置了id自增
@TableId(value = "uid",type = IdType.AUTO)
private Long id;
  • 可以在配置文件中进行设置统一的主键生成策略
# 设置统一的主键生成策略
id-type: auto

4.3 @TableField

  • 如果数据库中使用的是user_name,实体类中的字段使用的是userName,是可以对应上的,实体类会自动识别驼峰
  • 如果字段名和数据库中的字段名不一致也可以使用TableField注解去指定数据库中的字段
@TableField("user_name")
private String name;

4.4 @TableLogic

  • 就是假删除了,并没有在数据库中删除,但是查不出来
  • 实际执行的是update方法

5、条件构造器

5.1 QueryWrapper

  1. like、between、isNotNull的用法
  2. 降序、升序
  3. isNull
  4. 查询的优先级
  5. 查询指定的字段名
  6. 子查询的使用
@Test
public void test01(){
    // 查询username中包含a的,年龄在20-30岁之间的,email不为空的
    // SELECT uid AS id,user_name AS name,age,email,is_deleted FROM t_user WHERE is_deleted=0
    // AND (user_name LIKE ? AND age BETWEEN ? AND ? AND email IS NOT NULL)
    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
    queryWrapper.like("user_name","a")
    .between("age",20,30)
    .isNotNull("email");
    List<User> list = userMapper.selectList(queryWrapper);
    System.out.println(list);
}

@Test
public void test02(){
    // 查询用户信息,按照年龄上的降序,若年龄相同,则按照id的升序
    // SELECT uid AS id,user_name AS name,age,email,is_deleted FROM t_user
    // WHERE is_deleted=0 ORDER BY age DESC,uid ASC
    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
    queryWrapper.orderByDesc("age")
    .orderByAsc("uid");
    List<User> list = userMapper.selectList(queryWrapper);
    System.out.println(list);
}

@Test
public void test03(){
    // 删除email为空的用户记录
    // UPDATE t_user SET is_deleted=1 WHERE is_deleted=0 AND (email IS NULL)
    // 因此此处使用了逻辑删除 delete->update
    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
    queryWrapper.isNull("email");
    int delete = userMapper.delete(queryWrapper);
    System.out.println("delete:"+delete);
}

@Test
public void test04(){
    // 将年龄大于20并且用户名中包含a或邮箱为null的用户信息修改
    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
    queryWrapper.gt("age",20)
    .like("user_name","a")
    .or()
    .isNull("email");
    User user = new User();
    user.setName("panjie");
    user.setEmail("123@qq.com");
    int update = userMapper.update(user, queryWrapper);
    System.out.println("update:"+update);
}

@Test
public void test05(){
    // 将用户名中包含a并且(年龄大于20或邮箱为null())的用户信息修改
    // 优先 年龄大于20或邮箱为null()
    // lambda中的条件表达式优先执行
    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
    queryWrapper.like("user_name","a")
    .and(i->i.gt("age",20).or().isNull("email"));
    User user = new User();
    user.setName("panjie");
    user.setEmail("123@qq.com");
    int update = userMapper.update(user,queryWrapper);
    System.out.println(update);
}

@Test
public void test06(){
    // 查询指定的字段名
    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
    queryWrapper.select("user_name","age","email");
    List<Map<String, Object>> maps = userMapper.selectMaps(queryWrapper);
    System.out.println(maps);
}

@Test
public void test07(){
    // 查询id小于5的用户信息
    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
    queryWrapper.inSql("uid","select uid from t_user where uid <=10");
    List<User> users = userMapper.selectList(queryWrapper);
    System.out.println(users);
}

5.2 UpdateWrapper

@Test
public void test08(){
    // 将用户名中包含a并且(年龄大于20或邮箱为null())的用户信息修改
    // 优先 年龄大于20或邮箱为null()
    // lambda中的条件表达式优先执行
    UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
    updateWrapper.like("user_name","a")
    .and(i->i.gt("age",20).or().isNull("email"));
    updateWrapper.set("user_name","小潘").set("email","abc@123.mail");
    int update = userMapper.update(null, updateWrapper);
    System.out.println("update:"+update);
}

5.3 Condition

  • 先进行判断,再写查询条件
@Test
public void test09(){
    String username="a";
    Integer ageBegin = null;
    Integer ageEnd = 30;
    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
    queryWrapper.like(StringUtils.isNotBlank(username),"user_name",username)
    .ge(ageBegin != null,"age",ageBegin)
    .le(ageEnd != null,"age",ageEnd);
    List<User> users = userMapper.selectList(queryWrapper);
    System.out.println(users);
}

6、分页功能

6.1 分页插件

  1. 添加配置类
  2. 测试
@Configuration
@MapperScan("com.melon.mp.mapper") // 可以将主类中的注解移到这里
public class MybatisPlusConfig {

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

6.2 自定义分页

  1. UserMapper中定义接口方法
    1. page对象必须放在第一个
  2. yaml中配置配置类型别名多对应的包
  3. UserMapper.xml编写SQL
  4. 测试
@Repository
public interface UserMapper extends BaseMapper<User> {

    Map<String,Object> SelectById(Long id);
    
    // 	第一个参数必须是Page,第二个参数为查询条件
    Page<User> selectPageVo(@Param("page") Page<User> page, @Param("age") Integer age);
}
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  # 设置MyBatis-Plus的全局配置
  global-config:
    db-config:
      # 设置实体类所对应的表的统一前缀
      table-prefix: t_
      # 设置统一的主键生成策略
      id-type: auto
  # 配置类型别名多对应的包
  type-aliases-package: com.melon.mp.pojo
<mapper namespace="com.melon.mp.mapper.UserMapper">
  <select id="SelectById" resultType="map">
    select id,name,age,email from user where id = #{id}
  </select>

  <!-- Page<User> selectPageVo(@Param("page") Page<User> page, @Param("age") Integer age); -->
  <select id="selectPageVo" resultType="User">
    select uid,user_name,age,email from t_user where age >= #{age}
  </select>
</mapper>
  • 24
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值