Mybatis-Plus系列--基础实例

    技术2022-07-11  84

    其他网址

    mybatis-plus的使用 ------ 入门 - 简书

    创建工程

    配置

    本项目的gitee:https://gitee.com/shapeless/demo_MybtisPlus/tree/master/Simple

    项目结构

    pom.xml

    添加spring-boot-starter-web、mybatis-plus、mysql-connector-java、lombok依赖

    <?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 https://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>2.3.1.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.example</groupId> <artifactId>demo</artifactId> <version>0.0.1-SNAPSHOT</version> <name>demo</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.3.2</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <!-- <exclusions>--> <!-- <exclusion>--> <!-- <groupId>org.junit.vintage</groupId>--> <!-- <artifactId>junit-vintage-engine</artifactId>--> <!-- </exclusion>--> <!-- </exclusions>--> </dependency> <dependency> <groupId>org.junit.platform</groupId> <artifactId>junit-platform-launcher</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>

    application.yml

    添加数据库配置

    spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://127.0.0.1:3306/blog?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai username: root password: 222333 # mybatis-plus配置控制台打印完整带参数SQL语句 mybatis-plus: configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

    代码

    启动类(添加@MapperScan) 

    @SpringBootApplication @MapperScan("com.example.demo.mapper") public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }

    entity

    @Data @TableName(value = "tb_user")//指定表名 public class User{ //value与数据库主键列名一致,若实体类属性名与表主键列名一致可省略value //@TableId(value = "id",type = IdType.ASSIGN_UUID)//生成UUID private Integer id; private String name; //若表中列名不符合驼峰规则,可通过该注解指定数据库表中的列名,exist标明数据表中有没有对应列 @TableField(value = "last_name",exist = true) private String lastName; private String email; private Integer gender; private Integer age; }

    mapper

    @Repository //不加此注解也可以。此注解为了消除黄色波浪线 public interface UserMapper extends BaseMapper<User> { }

    创建数据库/表

    create database mp; use mp; create table tb_user( id int unsigned, name varchar(32), last_name varchar(32), email varchar(255), gender int unsigned, age int unsigned )ENGINE=InnoDB DEFAULT CHARSET=utf8;

    测试方法

    本文所有测试都用这种方法,直接在这个类里边添加测试项。先运行主类,再运行测试类。

    package com.example.demo; import com.example.demo.entity.User; import com.example.demo.mapper.UserMapper; import org.junit.jupiter.api.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest class DemoApplicationTests { @Autowired UserMapper userMapper; @Test public void testInsert(){ User employee = new User(); employee.setLastName("东方不败"); employee.setEmail("dfbb@163.com"); employee.setGender(1); employee.setAge(20); userMapper.insert(employee); //mybatisplus会自动把当前插入对象在数据库中的id写回到该实体中 System.out.println(employee.getId()); } }

    CRUD

    需求: 存在一张 tb_employee 表,且已有对应的实体类 Employee,实现tb_employee 表的 CRUD 操作我们需要做什么呢?基于 Mybatis: 需要编写 EmployeeMapper 接口,并在 EmployeeMapper.xml 映射文件中手动编写 CRUD 方法对应的sql语句。基于 MP: 只需要创建 EmployeeMapper 接口, 并继承 BaseMapper 接口。 我们已经有了Employee、tb_employee了,并且EmplopyeeMapper 也继承了BaseMapper了,接下来就使用crud方法。

    insert

    package com.example.demo; import com.example.demo.entity.User; import com.example.demo.mapper.UserMapper; import org.junit.jupiter.api.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest class DemoApplicationTests { @Autowired UserMapper userMapper; @Test public void testInsert(){ User employee = new User(); employee.setLastName("东方不败"); employee.setEmail("dfbb@163.com"); employee.setGender(1); employee.setAge(20); //返回值为影响的行数(本处是成功插入的行数) int ret = userMapper.insert(employee); System.out.println("ret:" + ret); //mybatisplus先自动生成id赋值给实体类的id列对应属性,再将其插入数据库 System.out.println("id:" + employee.getId()); } }

    打印结果 

    ==> Preparing: INSERT INTO tb_user ( id, last_name, email, gender, age ) VALUES ( ?, ?, ?, ?, ? ) ==> Parameters: 24bdb053a186a96f92dbd962f04ef183(String), 东方不败(String), dfbb@163.com(String), 1(Integer), 20(Integer) <== Updates: 1 Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@48976e6d] ret:1 id:24bdb053a186a96f92dbd962f04ef183

    update

    普通示例

    public void testUpdate(){ Employee employee = new Employee(); employee.setId(1); employee.setLastName("更新测试"); userMapper.updateById(employee);//根据id进行更新,没有传值的属性就不会更新 }

    将字段更新为null

    其他网址:Mybatis-plus 在不修改全局策略和字段注解的情况下将字段更新为null_lsqingfeng的博客-博客 

    将字段更新为null有三个方法

    将全局更新策略设置为空可以更新(不推荐)将这个字段设置为空可以更新。(不推荐)使用UpdateWrapper(推荐)。mp的版本大于3

    第1,2种可能导致别人在调用更新方法的时候不小心就把你的某些字段置为null 了。

    LambdaUpdateWrapper<User> wrapper = new LambdaUpdateWrapper<>(); wrapper.eq(User::getId(), 1); wrapper.set(User::getName(), null); userService.update(wrapper);

    select

    根据id查询

    User user = userMapper.selectById(1);

    根据条件查询一条数据

    QueryWrapper queryWrapper = new QueryWrapper(); queryWrapper.eq("name", "Tony"); queryWrapper.eq("age", 30); //若是数据库中符合传入的条件的记录有多条,那就不能用这个方法,会报错 User user = userMapper.selectOne(queryWrapper);

    这方法的sql语句就是where id = 1 and last_name = 更新测试,若是符合这个条件的记录不止一条,那么就会报错。

    根据条件查询多条数据

    当符合指定条件的记录数有多条时,上面那个方法就会报错,就应该用这个方法

    Map<String,Object> columnMap = new HashMap<>(); columnMap.put("last_name","东方不败");//写表中的列名 columnMap.put("gender","1"); List<User> users = userMapper.selectByMap(columnMap); System.out.println(users.size()); 查询条件用map集合封装,columnMap,写的是数据表中的列名,而非实体类的属性名。比如属性名为lastName,数据表中字段为last_name,这里应该写的是last_name。selectByMap方法返回值用list集合接收。

    通过id批量查询

    List<Integer> idList = new ArrayList<>(); idList.add(1); idList.add(2); idList.add(3); List<User> users = userMapper.selectBatchIds(idList); System.out.println(users);

    把需要查询的id都add到list集合中,然后调用selectBatchIds方法,传入该list集合即可,该方法返回的是对应id的所有记录,所有返回值也是用list接收。 

    分页查询 

    List<User> users = userMapper.selectPage(new Page<>(1,2),null); System.out.println(users);

    selectPage方法就是分页查询,在page中传入分页信息,后者为null的分页条件,这里先让其为null,讲了条件构造器再说其用法。这个分页其实并不是物理分页,而是内存分页。也就是说,查询的时候并没有limit语句。等配置了分页插件后才可以实现真正的分页。

    delete

    根据id删除

    userMapper.deleteById(1);

    根据条件删除

    Map<String,Object> columnMap = new HashMap<>(); columnMap.put("gender",0); columnMap.put("age",18); userMapper.deleteByMap(columnMap);

    该方法与selectByMap类似,将条件封装在columnMap中,然后调用deleteByMap方法,传入columnMap即可,返回值是Integer类型,表示影响的行数。

    根据id批量删除

    List<Integer> idList = new ArrayList<>(); idList.add(1); idList.add(2); userMapper.deleteBatchIds(idList);

    该方法和selectBatchIds类似,把需要删除的记录的id装进idList,然后调用deleteBatchIds,传入idList即可。 

     

     

    Processed: 0.009, SQL: 9