Mybatis-plus应用

1.导入依赖

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

2.添加application.yml配置

mybatis-plus:
  # xml文件路径
  mapper-locations: classpath:mapper/*.xml
  configuration:
    # 驼峰转换
    map-underscore-to-camel-case: true
    # 是否开启缓存
    cache-enabled: false
    # 打印sql
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  # 全局配置
  global-config:
    # 数据库字段驼峰下划线转换
    db-column-underline: true
    # id自增类型(数据库id自增)
    id-type: 0

三:MybatisPlusConfig

package com.xxxx.demo.config;

import com.baomidou.mybatisplus.annotation.DbType;
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;

/**
 * @ClassName MybatisPlusConfig
 * @Description
 * @Author Lishipu
 * @Date 2023/1/9 22:51
 * Version 1.0
 **/
@Configuration
@MapperScan("com.xxxx.demo.mapper")
public class MybatisPlusConfig{
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }
}

 

 

 

 

四.添加数据库对应实体类

例如:

 

 这个可以用代码生成器生成

4.添加Mapper文件

 

 

5。添加Service接口和添加Service实现类

 

 6.添加Controller

7.mybatis-plus中的增删改查

7.1查:

查询所有:

    //查询所有
    @GetMapping
    public List<User> findAll() {
        return userService.list();
    }

或者

   @Test
    public void selectList() {
        List<User> list =userService.selectList(null); 
System.out.println(list);
}

按照id查询

    //按照id寻找
    @GetMapping("/{id}")
    public User findOne(@PathVariable Integer id) {
        return userService.getById(id);
    }
QueryWrapper实体对象封装操作类实现多条加查询
//按照id查找,要封装Result,下面的接口都没有封装
@GetMapping("/username/{username}")
public Result findOne(@PathVariable String username) {
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("username",username);
        return Result.success(userService.getOne(queryWrapper));//返回用户名字等于username的一条数据,如果是多条记录的话是userService.selectList(queryWrapper);
 }
根据根据 entity 条件,删除记录,QueryWrapper实体对象封装操作类(可以为 null)
下方获取到queryWrapper后删除的查询条件为name字段为null的and年龄大于等于12的and email字段不为null的
public void delete() {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper
        .isNull("name")
        .ge("age", 12)
        .isNotNull("email");
        int delete = mapper.delete(queryWrapper);
        System.out.println("delete return count = " + delete);
        }
根据 Wrapper 条件,查询总记录数,查询名字等于"heheda"的记录的总数
public void selectCount() {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", "heheda");
        Integer count = userService.selectCount(queryWrapper);
        System.out.println(count);
    }

实现分页查询:

 //主页和分页查找
    @GetMapping("/page")
    public Page<User> findPage(@RequestParam Integer pageNum,
                               @RequestParam Integer pageSize,
                               @RequestParam(defaultValue = "") String username,
                               @RequestParam(defaultValue = "") String email,
                               @RequestParam(defaultValue = "") String address) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (!"".equals(username)) {
                queryWrapper.like("username", username);
        }
        if (!"".equals(email)) {
                queryWrapper.like("nickname", email);
        }
        if (!"".equals(address)) {
                queryWrapper.like("address", address);
        }
        queryWrapper.orderByDesc("id");return userService.page(new Page<>(pageNum, pageSize), queryWrapper);
    }
new一个hashmap,把条件放到map中,再把map放到条件中。
 
 //3、多条件去查询
        QueryWrapper queryWrapper2 = new QueryWrapper();
            //3.1、设置多条件
            Map<String,Object> map = new HashMap<>();
            map.put("age",20);
            map.put("name","张三");
            //3.2、map放进queryWrapper
        queryWrapper2.allEq(map);

7.2新增或者更新

 

// 新增或者更新
    @PostMapping
    public boolean save(@RequestBody User user) {
        return userService.saveOrUpdate(user);
    }

7.3删除

按照id删除

//按照id删除
    @DeleteMapping("/{id}")
    public Boolean delete(@PathVariable Integer id) {
        return userService.removeById(id);
    }
//批量删除
//批量删除
    @PostMapping("/del/batch")
    public boolean deleteBatch(@RequestBody List<Integer> ids) {
        return userService.removeByIds(ids);
    }
 //通过id删除
        userMapper.deleteById(1);

        //通过多条件id删除
        userMapper.deleteBatchIds(Arrays.asList(1,2,3));

        //通过条件删除
        QueryWrapper queryWrapper = new QueryWrapper ();
        queryWrapper.eq("name","张三");       //与查询相同
        userMapper.delete(queryWrapper);

        //通过条件删除---Map
        Map<String,Object> map = new HashMap<>();
        map.put("name","张三");
        userMapper.deleteByMap(map);

 

posted @ 2023-01-19 23:55  lipu123  阅读(41)  评论(0编辑  收藏  举报