MyBatisPlus - 2. Basic CRUD

content

1、BaseMapper

2. Insert

3. Delete

4. Modify

5. Query

6. Customize SQL (using xml configuration) for non-single table query and other operations

7, universal service

7.1 、 IService

7.2. Create Service interface and its implementation class

7.3. Number of test query records

7.4. Test batch addition


1、BaseMapper

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.baomidou.mybatisplus.core.mapper;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ExceptionUtils;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Param;

public interface BaseMapper<T> extends Mapper<T> {
    /**
     * 插入一条记录
     * @param entity 实体对象
     * @return
     */
    int insert(T entity);

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

    /**
     * 根据实体ID删除
     * @param entity 实体对象
     * @return
     */
    int deleteById(T entity);

    /**
     * 根据columnMap条件删除记录
     * @param columnMap 表字段map对象
     * @return
     */
    int deleteByMap(@Param("cm") Map<String, Object> columnMap);

    /**
     * 根据entity条件删除记录
     * @param queryWrapper 实体对象封装操作类(可以为 null,里面的 entity 用于生成 where 语句)
     * @return
     */
    int delete(@Param("ew") Wrapper<T> queryWrapper);

    /**
     * 删除(根据ID 批量删除)
     * @param idList 主键ID列表(不能为 null 以及 empty)
     * @return
     */
    int deleteBatchIds(@Param("coll") Collection<?> idList);

    /**
     * 根据 ID 修改,不会修改没有使用 set 注入属性的属性值
     * @param entity 实体对象
     * @return
     */
    int updateById(@Param("et") T entity);

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

    /**
     * 根据 ID 查询
     * @param id 主键ID
     * @return
     */
    T selectById(Serializable id);

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

    /**
     * 查询(根据 columnMap 条件)
     * @param columnMap 表字段 map 对象
     * @return
     */
    List<T> selectByMap(@Param("cm") Map<String, Object> columnMap);

    /**
     * 根据 entity 条件,查询一条记录
     * 查询一条记录,例如 qw.last("limit 1") 限制取一条记录, 注意:多条数据会报异常
     * @param queryWrapper 实体对象封装操作类(可以为 null)
     * @return
     */
    default T selectOne(@Param("ew") Wrapper<T> queryWrapper) {
        List<T> ts = this.selectList(queryWrapper);
        if (CollectionUtils.isNotEmpty(ts)) {
            if (ts.size() != 1) {
                throw ExceptionUtils.mpe("One record is expected, but the query result is multiple records", new Object[0]);
            } else {
                return ts.get(0);
            }
        } else {
            return null;
        }
    }

    /**
     * 根据 Wrapper 条件,查询总记录数
     * @param queryWrapper 实体对象封装操作类(可以为 null)
     * @return
     */
    default boolean exists(Wrapper<T> queryWrapper) {
        Long count = this.selectCount(queryWrapper);
        return null != count && count > 0L;
    }

    /**
     * 根据 Wrapper 条件,查询总记录数
     * @param queryWrapper 实体对象封装操作类(可以为 null)
     * @return
     */
    Long selectCount(@Param("ew") Wrapper<T> queryWrapper);

    /**
     * 根据 entity 条件,查询全部记录
     * @param queryWrapper 实体对象封装操作类(可以为 null)
     * @return
     */
    List<T> selectList(@Param("ew") Wrapper<T> queryWrapper);

    /**
     * 根据 Wrapper 条件,查询全部记录
     * @param queryWrapper 实体对象封装操作类(可以为 null)
     * @return
     */
    List<Map<String, Object>> selectMaps(@Param("ew") Wrapper<T> queryWrapper);

    /**
     * 根据 Wrapper 条件,查询全部记录
     * 注意: 只返回第一个字段的值
     * @param queryWrapper 实体对象封装操作类(可以为 null)
     * @return
     */
    List<Object> selectObjs(@Param("ew") Wrapper<T> queryWrapper);

    /**
     * 根据 entity 条件,查询全部记录(并翻页)
     * @param page 分页查询条件(可以为 RowBounds.DEFAULT)
     * @param queryWrapper 实体对象封装操作类(可以为 null)
     * @param <P>
     * @return
     */
    <P extends IPage<T>> P selectPage(P page, @Param("ew") Wrapper<T> queryWrapper);

    /**
     * 根据 Wrapper 条件,查询全部记录(并翻页)
     * @param page 分页查询条件
     * @param queryWrapper 实体对象封装操作类
     * @param <P>
     * @return
     */
    <P extends IPage<Map<String, Object>>> P selectMapsPage(P page, @Param("ew") Wrapper<T> queryWrapper);
}

2. Insert

    @Test
    public void testInsert(){
        User user = new User();
        user.setName("王五");
        user.setAge(46);
        user.setEmail("[email protected]");
        //
        int result = userMapper.insert(user);
        System.out.println("result = " + result);
        System.out.println("id = " + user.getId()); //这里获取的id是mybatis-plus通过雪花算法得到的
    }

3. Delete

    @Test
    public void testDelete(){
        // 通过id删除用户信息
        // DELETE FROM user WHERE id=?
        /*int result = userMapper.deleteById(1512743678382899202L);
        System.out.println("result = " + result);*/

        // 根据map集合中所设置的条件删除用户信息
        /*Map<String, Object> map = new HashMap<>();
        map.put("name", "王五");
        map.put("age", "46");
        // DELETE FROM user WHERE name = ? AND age = ?
        int result = userMapper.deleteByMap(map);
        System.out.println("result = " + result);*/

        // 通过多个ID实现批量删除
        List<Long> list = Arrays.asList(1512743901935067138L, 0L);
        // DELETE FROM user WHERE id IN ( ? , ? )
        int result = userMapper.deleteBatchIds(list);
        System.out.println("result = " + result);
    }

4. Modify

    @Test
    public void testUpdate(){
        User user = new User();
        user.setId(1L);
        user.setName("李四");
        user.setEmail("[email protected]");
        // UPDATE user SET name=?, email=? WHERE id=?
        // 不会修改没有set的属性值
        int result = userMapper.updateById(user);
        System.out.println("result = " + result);
    }

5. Query

    @Test
    public void testSelect(){
        // 通过ID查询用户信息
        /*// SELECT id,name,age,email FROM user WHERE id=?
        User user = userMapper.selectById(1L);
        System.out.println(user);*/

        // 根据多个ID查询多个用户信息
        /*List<Long> list = Arrays.asList(1L, 2L, 3L);
        // SELECT id,name,age,email FROM user WHERE id IN ( ? , ? , ? )
        List<User> users = userMapper.selectBatchIds(list);
        users.forEach(System.out::println);*/

        // 根据Map集合中的条件查询用户信息
        /*Map<String, Object> map = new HashMap<>();
        map.put("name", "Jack");
        map.put("age", 20);
        // SELECT id,name,age,email FROM user WHERE name = ? AND age = ?
        List<User> users = userMapper.selectByMap(map);
        users.forEach(System.out::println);*/

        // 查询所有数据
        // SELECT id,name,age,email FROM user
        List<User> users = userMapper.selectList(null);
        users.forEach(System.out::println);
    }

6. Customize SQL (using xml configuration) for non-single table query and other operations

The location of the XxxMapper.xml read by default in mybatis-plus is all xml files under src/main/resources/mapper (which can contain any layer directory), so we don't need to set the location of XxxMapper.xml by ourselves

 mapper interface: UserMapper

@Mapper
//@Repository  //将该类或接口标识为持久层组件
public interface UserMapper extends BaseMapper<User> {

    /**
     * 根据id查询用户信息为map集合
     * @param id
     * @return
     */
    Map<String, Object> selectMapById(Long id);

}

Configuration file: 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.zyj.mybatisplus.mapper.UserMapper">

    <!-- Map<String, Object> selectMapById(Long id); -->
    <select id="selectMapById" resultType="map">
        select id,name,age,email from user where id = #{id}
    </select>

</mapper>

testing method:

    @Test
    public void testSelectMapById(){
        Map<String, Object> map = userMapper.selectMapById(1L);
        System.out.println(map);
    }

Output result:

==>  Preparing: select id,name,age,email from user where id = ?
==> Parameters: 1(Long)
<==    Columns: id, name, age, email
<==        Row: 1, 李四, 18, [email protected]
<==      Total: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@65753040]
{name=李四, id=1, age=18, [email protected]}

7, universal service

illustrate:

  • General Service CRUD Encapsulates IService interface, further encapsulates CRUD Use get to query a single row remove Delete list Query collection page Paging prefix naming method to distinguish Mapper layer to avoid confusion,

  • The generic T is any entity object

  • It is recommended that if there is a possibility to customize the general Service method, please create your own IBaseService to inherit the base class provided by Mybatis-Plus

  • Official website address: CRUD interface | MyBatis-Plus

7.1 、 IService

There is an interface IService and its implementation class ServiceImpl in MyBatis-Plus, which encapsulates common business layer logic. For details, see the source code IService and ServiceImpl (because they are written by Chinese, so the comments inside are in Chinese)

7.2. Create Service interface and its implementation class

public interface UserService extends IService<User> {


}
@Service
// ServiceImpl<mapper接口, 实体类>
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {


}

7.3. Number of test query records

testing method:

public class MyBatisPlusServiceTest {

    @Autowired
    private UserService userService;

    @Test
    public void testGetCount(){
        // 查询总记录数
        // SELECT COUNT( * ) FROM user
        long count = userService.count();
        System.out.println("总记录数 = " + count);
    }

}

Output result:

==>  Preparing: SELECT COUNT( * ) FROM user
==> Parameters: 
<==    Columns: COUNT( * )
<==        Row: 5
<==      Total: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@238bfd6c]
总记录数 = 5

7.4. Test batch addition

testing method: 

    @Test
    public void testInsertMore(){
        // 批量添加
        // Preparing: INSERT INTO user ( id, name, age, email ) VALUES ( ?, ?, ?, ? )
        List<User> list = new ArrayList<>();
        for(int i = 0; i < 10; i++){
            User user = new User();
            user.setName("张" + i);
            user.setAge(20 + i);
            user.setEmail("zhang" + i + "@qq.com");
            list.add(user);
        }
        boolean b = userService.saveBatch(list);
        System.out.println(b);
    }

Output result:

==>  Preparing: INSERT INTO user ( id, name, age, email ) VALUES ( ?, ?, ?, ? )
==> Parameters: 1513090537404141570(Long), 张0(String), 20(Integer), [email protected](String)
==> Parameters: 1513090537634828289(Long), 张1(String), 21(Integer), [email protected](String)
==> Parameters: 1513090537634828290(Long), 张2(String), 22(Integer), [email protected](String)
==> Parameters: 1513090537634828291(Long), 张3(String), 23(Integer), [email protected](String)
==> Parameters: 1513090537634828292(Long), 张4(String), 24(Integer), [email protected](String)
==> Parameters: 1513090537634828293(Long), 张5(String), 25(Integer), [email protected](String)
==> Parameters: 1513090537634828294(Long), 张6(String), 26(Integer), [email protected](String)
==> Parameters: 1513090537634828295(Long), 张7(String), 27(Integer), [email protected](String)
==> Parameters: 1513090537634828296(Long), 张8(String), 28(Integer), [email protected](String)
==> Parameters: 1513090537634828297(Long), 张9(String), 29(Integer), [email protected](String)
true

Guess you like

Origin blog.csdn.net/Mr_zhangyj/article/details/124063611