mybatis-plus高效开发,mybatis的好兄弟

导入依赖:
加粗样式

<?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><groupId>com.huxingxing.mp</groupId>
    <artifactId>huxingxing-mybatis-plus</artifactId>
    <version>1.0-SNAPSHOT</version>
    <modules>
        <module>huxingxing-mybatis-plus-simple</module>
    </modules>
    <packaging>pom</packaging><dependencies>
              <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus</artifactId>
            <version>3.1.1</version>
        </dependency>
       
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
     
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.11</version>
        </dependency>
       
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
            <version>1.18.4</version>
        </dependency>
        
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.6.4</version>
        </dependency>
        
    </dependencies><build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build></project>

Mybatis与Mybatis-Plus整合。

2.3.1、创建子Module

<?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">
    <parent>
        <artifactId>huxingxing-mybatis-plus</artifactId>
        <groupId>com.huxingxing.mp</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <packaging>jar</packaging><artifactId>huxingxing-mybatis-plus</artifactId></project>

Mybatis实现查询User
第一步,编写mybatis-config.xml文件:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://127.0.0.1:3306/mp?useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true&useSSL=false"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="UserMapper.xml"/>
    </mappers>
</configuration>

第二步,编写User实体对象:(这里使用lombok进行了进化bean操作)

package com.huxingxing.mp.simple.pojo;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;@Data
@NoArgsConstructor
@AllArgsConstructor
@TableName("tb_user")
public class User {
     private Long id;
    private String username;
    private String password;
    private String name;
    private Integer age;
    private String email;
}

第三步,编写UserMapper接口:

package com.huxingxing.mp.simple.mapper;import com.huxingxing.mp.simple.pojo.User;import java.util.List;public interface UserMapper {
     
​
    List<User> findAll();}

第四步,编写UserMapper.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.huxingxing.mp.simple.mapper.UserMapper"><select id="findAll" resultType="com.huxingxing.mp.simple.pojo.User">
      select * from tb_user
    </select>
</mapper>

第五步,编写TestMybatis测试用例:

package com.huxingxing.mp.simple;import com.huxingxing.mp.simple.mapper.UserMapper;
import com.huxingxing.mp.simple.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;import java.io.InputStream;
import java.util.List;public class TestMybatis {
     @Test
    public void testUserList() throws Exception{
     
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
​
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        List<User> list = userMapper.findAll();
        for (User user : list) {
     
            System.out.println(user);
        }}}


测试结果:

User(id=1, userName=null, password=123456, name=张三, age=18, [email protected])
User(id=2, userName=null, password=123456, name=李四, age=20, [email protected])
User(id=3, userName=null, password=123456, name=王五, age=28, [email protected])
User(id=4, userName=null, password=123456, name=赵六, age=21, [email protected])
User(id=5, userName=null, password=123456, name=孙七, age=24, [email protected])
2.3.3、Mybatis+MP实现查询User
第一步,将UserMapper继承BaseMapper,将拥有了BaseMapper中的所有方法:

package com.huxingxing.mp.simple.mapper;import com.huxingxing.mp.simple.pojo.User;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;import java.util.List;public interface UserMapper extends BaseMapper<User> {
     
​
    List<User> findAll();}


第二步,使用MP中的MybatisSqlSessionFactoryBuilder进程构建:

package com.huxingxing.mp.simple;import com.huxingxing.mp.simple.mapper.UserMapper;
import com.huxingxing.mp.simple.pojo.User;
import com.baomidou.mybatisplus.core.MybatisSqlSessionFactoryBuilder;
import org.apache.ibatis.io.Resources;import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;import java.io.InputStream;
import java.util.List;public class TestMybatisPlus {
     @Test
    public void testUserList() throws Exception{
     
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        //这里使用的是MP中的 //com.baomidou.mybatisplus.core.
        //MybatisSqlSessionFactoryBuilder;
        SqlSessionFactory sqlSessionFactory = new MybatisSqlSessionFactoryBuilder().build(inputStream);
        SqlSession sqlSession = sqlSessionFactory.openSession();
​
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);// 可以调用BaseMapper中定义的方法
        List<User> list = userMapper.selectList(null);
        for (User user : list) {
     
            System.out.println(user);
        }}}


User(id=1, userName=zhangsan, password=123456, name=张三, age=18, [email protected])
User(id=2, userName=lisi, password=123456, name=李四, age=20, [email protected])
User(id=3, userName=wangwu, password=123456, name=王五, age=28, [email protected])
User(id=4, userName=zhaoliu, password=123456, name=赵六, age=21, [email protected])
User(id=5, userName=sunqi, password=123456, name=孙七, age=24, [email protected])

2.4、Spring + Mybatis + MP
引入了Spring框架,数据源、构建等工作就交给了Spring管理。

创建子Module

<?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">
    <parent>
        <artifactId>huxingxing-mybatis-plus</artifactId>
        <groupId>com.huxingxing.mp</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion><artifactId>huxingxing-mybatis-plus-spring</artifactId><properties>
        <spring.version>5.1.6.RELEASE</spring.version>
    </properties><dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${
     spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${
     spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${
     spring.version}</version>
        </dependency>
    </dependencies>



2.4.2、实现查询User
第一步,编写jdbc.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/mp?useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true&useSSL=false
jdbc.username=root
jdbc.password=root
第二步,编写applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd"><context:property-placeholder location="classpath:*.properties"/><!-- 定义数据源 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
          destroy-method="close">
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="maxActive" value="10"/>
        <property name="minIdle" value="5"/>
    </bean><!--这里使用MP提供的sqlSessionFactory,完成了Spring与MP的整合-->
    <bean id="sqlSessionFactory" class="com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
    </bean><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.huxingxing.mp.simple.mapper"/>
    </bean></beans>


第三步,编写User对象以及UserMapper接口:

package com.huxingxing.mp.simple.pojo;import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;@Data
@NoArgsConstructor
@AllArgsConstructor
@TableName("tb_user")
public class User {
     private Long id;
    private String userName;
    private String password;
    private String name;
    private Integer age;
    private String email;
}

第四步,编写测试用例:

package com.huxingxing.mp.simple;import com.huxingxing.mp.simple.mapper.UserMapper;
import com.huxingxing.mp.simple.pojo.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import java.util.List;@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class TestSpringMP {
     @Autowired
    private UserMapper userMapper;@Test
    public void testSelectList(){
     
        List<User> users = this.userMapper.selectList(null);
        for (User user : users) {
     
            System.out.println(user);
        }
    }}

测试:

User(id=1, userName=zhangsan, password=123456, name=张三, age=18, [email protected])
User(id=2, userName=lisi, password=123456, name=李四, age=20, [email protected])
User(id=3, userName=wangwu, password=123456, name=王五, age=28, [email protected])
User(id=4, userName=zhaoliu, password=123456, name=赵六, age=21, [email protected])
User(id=5, userName=sunqi, password=123456, name=孙七, age=24, [email protected])

SpringBoot + Mybatis + MP
使用SpringBoot将进一步的简化MP的整合

导入依赖

<?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>2.1.4.RELEASE</version>
    </parent><groupId>com.huxingxing.mp</groupId>
    <artifactId>huxingxing-mp-springboot</artifactId>
    <version>1.0-SNAPSHOT</version><dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency><!--简化代码的工具包-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <!--mybatis-plus的springboot支持-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.1.1</version>
        </dependency>
        <!--mysql驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
        </dependency></dependencies><build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build></project>

编写application.properties

spring.application.name = huxingxing-mp-springboot
​
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/mp?useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true&useSSL=false
spring.datasource.username=root
spring.datasource.password=root
package com.huxingxing.mp;import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;@MapperScan("com.huxingxing.mp.mapper") //设置mapper接口的扫描包
@SpringBootApplication
public class MyApplication {
     public static void main(String[] args) {
     
        SpringApplication.run(MyApplication.class, args);
    }}

编写测试

package com.huxingxing.mp;import com.huxingxing.mp.mapper.UserMapper;
import com.huxingxing.mp.pojo.User;
import org.junit.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;import java.util.List;@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
     @Autowired
    private UserMapper userMapper;@Test
    public void testSelect() {
     
        List<User> userList = userMapper.selectList(null);
        for (User user : userList) {
     
            System.out.println(user);
        }
    }

}
测试:
User(id=1, userName=zhangsan, password=123456, name=张三, age=18, [email protected])
User(id=2, userName=lisi, password=123456, name=李四, age=20, [email protected])
User(id=3, userName=wangwu, password=123456, name=王五, age=28, [email protected])
User(id=4, userName=zhaoliu, password=123456, name=赵六, age=21, [email protected])
User(id=5, userName=sunqi, password=123456, name=孙七, age=24, [email protected])

通用CRUD
通过前面的学习,我们了解到通过继承BaseMapper就可以获取到各种各样的单表操作,接下来我们将详细讲解这些操作。

插入操作
方法定义

/**

  • 插入一条记录
  • @param entity 实体对象
    */
    int insert(T entity);

测试

package com.huxingxing.mp;import com.huxingxing.mp.mapper.UserMapper;
import com.huxingxing.mp.pojo.User;
import org.junit.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;import java.util.List;@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
     @Autowired
    private UserMapper userMapper;@Test
    public void testInsert(){
     
        User user = new User();
        user.setAge(20);
        user.setEmail("[email protected]");
        user.setUserName("huxingxing");
        user.setPassword("123456");int result = this.userMapper.insert(user); //返回的result是受影响的行数,并不是自增后的id
        System.out.println("result = " + result); 
        System.out.println(user.getId()); //自增后的id会回填到对象中
    }}

更新操作
在MP中,更新操作有2种,一种是根据id更新,另一种是根据条件更新。

根据id更新
方法定义:

   /**
     * 根据 ID 修改
     *
     * @param entity 实体对象
     */
    int updateById(@Param(Constants.ENTITY) T entity);

测试:

@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
     @Autowired
    private UserMapper userMapper;@Test
    public void testUpdateById() {
     
        User user = new User();
        user.setId(6L); //主键
        user.setAge(21); //更新的字段//根据id更新,更新不为null的字段
        this.userMapper.updateById(user);
    }}

根据条件更新
方法定义:

/**

  • 根据 whereEntity 条件,更新记录
  • @param entity 实体对象 (set 条件值,可以为 null)
  • @param updateWrapper 实体对象封装操作类(可以为 null,里面的 entity 用于生成 where 语句)
    */
    int update(@Param(Constants.ENTITY) T entity, @Param(Constants.WRAPPER) Wrapper updateWrapper);


测试用例:

package com.huxingxing.mp;import com.huxingxing.mp.mapper.UserMapper;
import com.huxingxing.mp.pojo.User;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import net.minidev.json.writer.UpdaterMapper;
import org.junit.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;import java.util.List;@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
     @Autowired
    private UserMapper userMapper;@Test
    public void testUpdate() {
     
        User user = new User();
        user.setAge(22); //更新的字段//更新的条件
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("id", 6);//执行更新操作
        int result = this.userMapper.update(user, wrapper);
        System.out.println("result = " + result);
    }}

或者,通过UpdateWrapper进行更新:

    @Test
    public void testUpdate() {
     
        //更新的条件以及字段
        UpdateWrapper<User> wrapper = new UpdateWrapper<>();
        wrapper.eq("id", 6).set("age", 23);//执行更新操作
        int result = this.userMapper.update(null, wrapper);
        System.out.println("result = " + result);
    }

删除操作
deleteById
方法定义:

/**
 * 根据 ID 删除
 *
 * @param id 主键ID
 */
int deleteById(Serializable id);

测试:

package com.huxingxing.mp;import com.huxingxing.mp.mapper.UserMapper;
import org.junit.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
public class UserMapperTest {
     @Autowired
    private UserMapper userMapper;@Test
    public void testDeleteById() {
     
        //执行删除操作
        int result = this.userMapper.deleteById(6L);
        System.out.println("result = " + result);
    }}

deleteByMap
方法定义:

/**
 * 根据 columnMap 条件,删除记录
 *
 * @param columnMap 表字段 map 对象
 */
int deleteByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);
package com.huxingxing.mp;import com.huxingxing.mp.mapper.UserMapper;
import org.junit.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;import java.util.HashMap;
import java.util.Map;@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
     @Autowired
    private UserMapper userMapper;@Test
    public void testDeleteByMap() {
     
        Map<String, Object> columnMap = new HashMap<>();
        columnMap.put("age",20);
        columnMap.put("name","张三");//将columnMap中的元素设置为删除的条件,多个之间为and关系
        int result = this.userMapper.deleteByMap(columnMap);
        System.out.println("result = " + result);
    }}

delete
方法定义:

/**
 * 根据 entity 条件,删除记录
 *
 * @param wrapper 实体对象封装操作类(可以为 null)
 */
int delete(@Param(Constants.WRAPPER) Wrapper<T> wrapper);

测试用例:

package com.huxingxing.mp;import com.huxingxing.mp.mapper.UserMapper;
import com.huxingxing.mp.pojo.User;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.junit.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;import java.util.HashMap;
import java.util.Map;@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
     @Autowired
    private UserMapper userMapper;@Test
    public void testDeleteByMap() {
     
        User user = new User();
        user.setAge(20);
        user.setName("张三");//将实体对象进行包装,包装为操作条件
        QueryWrapper<User> wrapper = new QueryWrapper<>(user);int result = this.userMapper.delete(wrapper);
        System.out.println("result = " + result);
    }}

deleteBatchIds

方法定义:

 /**
     * 删除(根据ID 批量删除)
     *
     * @param idList 主键ID列表(不能为 null 以及 empty)
     */
    int deleteBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);
package com.huxingxing.mp;import com.huxingxing.mp.mapper.UserMapper;
import org.junit.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;import java.util.Arrays;@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
     @Autowired
    private UserMapper userMapper;@Test
    public void testDeleteByMap() {
     
        //根据id集合批量删除
        int result = this.userMapper.deleteBatchIds(Arrays.asList(1L,10L,20L));
        System.out.println("result = " + result);
    }}

查询操作
MP提供了多种查询操作,包括根据id查询、批量查询、查询单条数据、查询列表、分页查询等操作。

selectById
方法定义:

   /**
     * 根据 ID 查询
     *
     * @param id 主键ID
     */
    T selectById(Serializable id);
package com.huxingxing.mp;import com.huxingxing.mp.mapper.UserMapper;
import com.huxingxing.mp.pojo.User;
import org.junit.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
public class UserMapperTest {
     @Autowired
    private UserMapper userMapper;@Test
    public void testSelectById() {
     
        //根据id查询数据
        User user = this.userMapper.selectById(2L);
        System.out.println("result = " + user);
    }}

结果:
result = User(id=2, userName=lisi, password=123456, name=李四, age=20, [email protected], address=null)

selectBatchIds
方法定义:

/**
 * 查询(根据ID 批量查询)
 *
 * @param idList 主键ID列表(不能为 null 以及 empty)
 */
List<T> selectBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);

测试用例:

package com.huxingxing.mp;import com.huxingxing.mp.mapper.UserMapper;
import com.huxingxing.mp.pojo.User;
import org.junit.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;import java.util.Arrays;
import java.util.List;@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
     @Autowired
    private UserMapper userMapper;@Test
    public void testSelectBatchIds() {
     
        //根据id集合批量查询
        List<User> users = this.userMapper.selectBatchIds(Arrays.asList(2L, 3L, 10L));
        for (User user : users) {
     
            System.out.println(user);
        }
    }}

结果:
User(id=2, userName=lisi, password=123456, name=李四, age=20, [email protected], address=null)
User(id=3, userName=wangwu, password=123456, name=王五, age=28, [email protected], address=null)

selectOne

方法定义:
/**
 * 根据 entity 条件,查询一条记录
 *
 * @param queryWrapper 实体对象封装操作类(可以为 null)
 */
T selectOne(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
测
``

```java
package com.huxingxing.mp;import com.huxingxing.mp.mapper.UserMapper;
import com.huxingxing.mp.pojo.User;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.junit.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
public class UserMapperTest {
     @Autowired
    private UserMapper userMapper;@Test
    public void testSelectOne() {
     
        QueryWrapper<User> wrapper = new QueryWrapper<User>();
        wrapper.eq("name", "李四");//根据条件查询一条数据,如果结果超过一条会报错
        User user = this.userMapper.selectOne(wrapper);
        System.out.println(user);
    }}

结果:
User(id=2, userName=lisi, password=123456, name=李四, age=20, [email protected], address=null)

selectCount
方法定义:

/**
 * 根据 Wrapper 条件,查询总记录数
 *
 * @param queryWrapper 实体对象封装操作类(可以为 null)
 */
Integer selectCount(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
package com.huxingxing.mp;import com.huxingxing.mp.mapper.UserMapper;
import com.huxingxing.mp.pojo.User;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.junit.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
public class UserMapperTest {
     @Autowired
    private UserMapper userMapper;@Test
    public void testSelectCount() {
     
        QueryWrapper<User> wrapper = new QueryWrapper<User>();
        wrapper.gt("age", 23); //年龄大于23岁//根据条件查询数据条数
        Integer count = this.userMapper.selectCount(wrapper);
        System.out.println("count = " + count);
    }}

结果:​
count = 2

selectList
方法定义:

/**
 * 根据 entity 条件,查询全部记录
 *
 * @param queryWrapper 实体对象封装操作类(可以为 null)
 */
List<T> selectList(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
package com.huxingxing.mp;import com.huxingxing.mp.mapper.UserMapper;
import com.huxingxing.mp.pojo.User;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.junit.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;import java.util.List;@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
     @Autowired
    private UserMapper userMapper;@Test
    public void testSelectList() {
     
        QueryWrapper<User> wrapper = new QueryWrapper<User>();
        wrapper.gt("age", 23); //年龄大于23岁//根据条件查询数据
        List<User> users = this.userMapper.selectList(wrapper);
        for (User user : users) {
     
            System.out.println("user = " + user);
        }
    }}

user = User(id=3, userName=wangwu, password=123456, name=王五, age=28, [email protected], address=null)
user = User(id=5, userName=sunqi, password=123456, name=孙七, age=24, [email protected], address=null)

selectPage

方法定义:

/**
 * 根据 entity 条件,查询全部记录(并翻页)
 *
 * @param page         分页查询条件(可以为 RowBounds.DEFAULT)
 * @param queryWrapper 实体对象封装操作类(可以为 null)
 */
IPage<T> selectPage(IPage<T> page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
package com.huxingxing.mp;import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;@Configuration
@MapperScan("com.huxingxing.mp.mapper") //设置mapper接口的扫描包
public class MybatisPlusConfig {
     /**
     * 分页插件
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
     
        return new PaginationInterceptor();
    }
}
package com.huxingxing.mp;import com.huxingxing.mp.mapper.UserMapper;
import com.huxingxing.mp.pojo.User;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.junit.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;import java.util.List;@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
     @Autowired
    private UserMapper userMapper;@Test
    public void testSelectPage() {
     
        QueryWrapper<User> wrapper = new QueryWrapper<User>();
        wrapper.gt("age", 20); //年龄大于20岁
​
        Page<User> page = new Page<>(1,1);//根据条件查询数据
        IPage<User> iPage = this.userMapper.selectPage(page, wrapper);
        System.out.println("数据总条数:" + iPage.getTotal());
        System.out.println("总页数:" + iPage.getPages());
​
​
        List<User> users = iPage.getRecords();
        for (User user : users) {
     
            System.out.println("user = " + user);
        }
    }}

结果:

数据总条数:3
总页数:3
user = User(id=3, userName=wangwu, password=123456, name=王五, age=28, [email protected], address=null)

你可能感兴趣的:(mybatisplus,java)