MyBatis-Plus,SimpleQuery查询

15 篇文章 0 订阅
2 篇文章 0 订阅

对list查询后的结果用Stream流进行了一些封装,使其可以返回一些指定结果,简洁了api的调用,这种调用方式不用注入bean、不用注入bean、不用注入bean,通过实体类class查询
**SimpleQuery.list()、SimpleQuery.keyMap()**较常用

         <!--低版本没有这个工具类-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.3/version>
        </dependency>
// 获取ID
List<Long> list = SimpleQuery.list(new QueryWrapper<HssTypePropertyEntity>()
    .eq("type_id",5).lambda(), HssTypePropertyEntity::getId);

// 以typeId为key分组
Map<Long, HssEquipmentEntity> map = 
    SimpleQuery.keyMap(new QueryWrapper<HssEquipmentEntity>()
    .eq("type_id", 5).lambda(),
    HssEquipmentEntity::getTypeId);
// 查询角色的隐藏ID,以角色ID分组
Map<Long, List<Long>> columnMap =
    SimpleQuery.group(new QueryWrapper<SysRoleColumnEntity>().lambda(), 
    SysRoleColumnEntity::getRoleId, 
    Collectors.mapping(SysRoleColumnEntity::getColumnId, Collectors.toList()));

操作实例:

 // 我要这个表里对应条件的用户,用id作为key给我一个map
        Map<Long, Entity> idEntityMap = SimpleQuery.keyMap(Wrappers.<Entity>lambdaQuery().eq(Entity::getId, 1L), Entity::getId);
        // 校验结果
        Entity entity = new Entity();
        entity.setId(1L);
        entity.setName("ruben");
        Assert.isTrue(idEntityMap.equals(Collections.singletonMap(1L, entity)), "Ops!");

        // 如果我只想要id和name组成的map
        Map<Long, String> idNameMap = SimpleQuery.map(Wrappers.lambdaQuery(), Entity::getId, Entity::getName);
        // 校验结果
        Map<Long, String> map = new HashMap<>(1 << 2);
        map.put(1L, "ruben");
        map.put(2L, null);
        Assert.isTrue(idNameMap.equals(map), "Ops!");
    }

    @Test
    public void testGroup() {
        // 我需要相同名字的用户的分为一组,再造一条数据
        doTestAutoCommit(m -> {
            Entity entity = new Entity();
            entity.setId(3L);
            entity.setName("ruben");
            m.insert(entity);
        });

        // 简单查询
        Map<String, List<Entity>> nameUsersMap = SimpleQuery.group(Wrappers.lambdaQuery(), Entity::getName);

        // 校验结果
        Map<String, List<Entity>> map = new HashMap<>(1 << 2);
        Entity chao = new Entity();
        chao.setId(2L);
        chao.setName(null);
        map.put(null, Collections.singletonList(chao));

        Entity ruben = new Entity();
        ruben.setId(1L);
        ruben.setName("ruben");
        Entity ruben2 = new Entity();
        ruben2.setId(3L);
        ruben2.setName("ruben");
        map.put("ruben", Arrays.asList(ruben, ruben2));
        Assert.isTrue(nameUsersMap.equals(map), "Ops!");

        // 解锁高级玩法:
        // 获取Map<name,List<id>>
        Map<String, List<Long>> nameIdMap = SimpleQuery.group(Wrappers.lambdaQuery(), Entity::getName, Collectors.mapping(Entity::getId, Collectors.toList()));
        // 获取Map<name,个数>
        Map<String, Long> nameCountMap = SimpleQuery.group(Wrappers.lambdaQuery(), Entity::getName, Collectors.counting());
        // ...超多花样
    }

    @Override
    protected String tableDataSql() {
        return "insert into entity(id,name) values(1,'ruben'),(2,null);";
    }

    @Override
    protected List<String> tableSql() {
        return Arrays.asList("drop table if exists entity", "CREATE TABLE IF NOT EXISTS entity (" +
            "id BIGINT NOT NULL," +
            "name VARCHAR(30) NULL DEFAULT NULL," +
            "PRIMARY KEY (id))");
    }


当然原来的查询也可以,只是还需要注入bean才能操作,listObjs(wrapper,mapper)

List<Long> strings = 
hssTypePropertyService.listObjs(new QueryWrapper<HssTypePropertyEntity>()
    .select("id").eq("type_id", 5)
    ,i->Long.valueOf(i.toString()));

ActiveRecord (查询)模式
说明:
● 实体类只需继承 Model 类即可进行强大的 CRUD 操作
● 需要项目中已注入对应实体的BaseMapper
实体继承 Model,调用自mapper,省去注入!

@Data
@TableName(value = "hss_history", autoResultMap = true)
public class HssHistoryEntity extends Model<HssHistoryEntity> implements Serializable {
    private static final long serialVersionUID = 1L;
    @TableId
    private Long id;
    // json映射,autoResultMap必须开启,写了xml查询需要resultMap映射字段
    //查询映射<result column="data" property="data" typeHandler="com.baomidou.mybatisplus.extension.handlers.JacksonTypeHandler" javaType="com.alibaba.fastjson.JSONObject"/>
    //更新映射#{e.data,jdbcType=VARCHAR,typeHandler=com.baomidou.mybatisplus.extension.handlers.JacksonTypeHandler},
    @TableField(typeHandler = JacksonTypeHandler.class)
    private JSONObject data;  
}

创建对象直接就可以使用crud,省去注入

HssHistoryEntity entity = new HssHistoryEntity();
// 创建对象直接就有crud了
entity.insert();
entity.selectList(new QueryWrapper<HssHistoryEntity>());
entity.updateById();
entity.deleteById();

Db类

说明: 版本需要3.5.3及以上

使用静态调用的方式,执行CRUD方法,避免Spring环境下Service循环注入、简洁代码,提升效率
需要项目中已注入对应实体的BaseMapper
完整使用方式见: 测试用例

(opens new window)
对于参数为Wrapper的,需要在Wrapper中传入Entity或者EntityClass供寻找对应的Mapper
不建议在循环中调用,如果是批量保存,建议将数据构造好后使用 Db.saveBatch(数据) 保存

package com.baomidou.mybatisplus.test.toolkit;

import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.exceptions.TooManyResultsException;
import org.apache.ibatis.plugin.Interceptor;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.UpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.baomidou.mybatisplus.test.BaseDbTest;
import com.baomidou.mybatisplus.test.sqlrunner.Entity;
import com.baomidou.mybatisplus.test.sqlrunner.EntityMapper;

/**
 * 以静态方式调用Service中的函数
 *
 * @author VampireAchao
 * @since 2022-05-03
 */
class DbTest extends BaseDbTest<EntityMapper> {

    @Test
    void testSave() {
        Entity entity = new Entity();
        entity.setName("ruben");
        boolean isSuccess = Db.save(entity);
        Assertions.assertTrue(isSuccess);
        Assertions.assertEquals(3L, Db.count(Entity.class));
    }

    @Test
    void testSaveBatch() {
        List<Entity> list = Arrays.asList(new Entity(), new Entity());
        boolean isSuccess = Db.saveBatch(list);
        Assertions.assertTrue(isSuccess);
        Assertions.assertEquals(4, Db.count(Entity.class));
    }

    @Test
    void testSaveOrUpdateBatch() {
        Entity entity = new Entity();
        entity.setId(1L);
        entity.setName("cat");
        List<Entity> list = Arrays.asList(new Entity(), entity);
        boolean isSuccess = Db.saveOrUpdateBatch(list);
        Assertions.assertTrue(isSuccess);
        Assertions.assertEquals(3, Db.count(Entity.class));
    }

    @Test
    void testRemoveById() {
        Entity entity = new Entity();
        entity.setId(1L);
        boolean isSuccess = Db.removeById(entity);
        Assertions.assertTrue(isSuccess);
        Assertions.assertEquals(1, Db.count(Entity.class));
        isSuccess = Db.removeById(2L, Entity.class);
        Assertions.assertTrue(isSuccess);
        Assertions.assertEquals(0, Db.count(Entity.class));
    }

    @Test
    void testUpdateById() {
        Entity entity = new Entity();
        entity.setId(1L);
        entity.setName("bee bee I'm a sheep");
        boolean isSuccess = Db.updateById(entity);
        Assertions.assertTrue(isSuccess);
        Assertions.assertEquals("bee bee I'm a sheep", Db.getById(1L, Entity.class).getName());
    }

    @Test
    void testUpdate() {
        boolean isSuccess = Db.update(Wrappers.lambdaUpdate(Entity.class).eq(Entity::getId, 1L).set(Entity::getName, "be better"));
        Assertions.assertTrue(isSuccess);
        Assertions.assertEquals("be better", Db.getById(1L, Entity.class).getName());

        Entity entity = new Entity();
        entity.setId(1L);
        entity.setName("bee bee I'm a sheep");
        isSuccess = Db.update(entity, Wrappers.lambdaQuery(Entity.class).eq(Entity::getId, 1L));
        Assertions.assertTrue(isSuccess);
        Assertions.assertEquals("bee bee I'm a sheep", Db.getById(1L, Entity.class).getName());
    }

    @Test
    void testUpdateBatchById() {
        Entity sheep = new Entity();
        sheep.setId(1L);
        sheep.setName("bee bee I'm a sheep");

        Entity ruben = new Entity();
        ruben.setId(2L);
        ruben.setName("rabbit");
        boolean isSuccess = Db.updateBatchById(Arrays.asList(sheep, ruben));
        Assertions.assertTrue(isSuccess);
        Assertions.assertEquals("bee bee I'm a sheep", Db.getById(1L, Entity.class).getName());
        Assertions.assertEquals("rabbit", Db.getById(2L, Entity.class).getName());
    }

    @Test
    void testRemove() {
        boolean isSuccess = Db.remove(Wrappers.lambdaQuery(Entity.class).eq(Entity::getId, 1L));
        Assertions.assertTrue(isSuccess);
        Assertions.assertEquals(1, Db.count(Entity.class));
    }

    @Test
    void testRemoveByIds() {
        boolean isSuccess = Db.removeByIds(Arrays.asList(1L, 2L), Entity.class);
        Assertions.assertTrue(isSuccess);
        Assertions.assertEquals(0, Db.count(Entity.class));
    }

    @Test
    void testRemoveByMap() {
        boolean isSuccess = Db.removeByMap(Collections.singletonMap("id", 1L), Entity.class);
        Assertions.assertTrue(isSuccess);
        Assertions.assertEquals(1, Db.count(Entity.class));
    }

    @Test
    void testSaveOrUpdate() {
        Entity entity = new Entity();
        entity.setId(null);
        entity.setName("bee bee I'm a sheep");
        boolean isSuccess = Db.saveOrUpdate(entity);
        Assertions.assertTrue(isSuccess);
        Assertions.assertEquals("bee bee I'm a sheep", Db.getById(entity.getId(), Entity.class).getName());

        entity.setName("be better");
        isSuccess = Db.saveOrUpdate(entity, Wrappers.lambdaQuery(Entity.class).eq(Entity::getId, entity.getId()));
        Assertions.assertTrue(isSuccess);
        Assertions.assertEquals("be better", Db.getById(entity.getId(), Entity.class).getName());
    }

    @Test
    void testGetOne() {
        LambdaQueryWrapper<Entity> wrapper = Wrappers.lambdaQuery(Entity.class);
        Assertions.assertThrows(TooManyResultsException.class, () -> Db.getOne(wrapper));
        Entity one = Db.getOne(wrapper, false);
        Assertions.assertNotNull(one);
        Entity entity = new Entity();
        entity.setId(1L);
        one = Db.getOne(entity);
        Assertions.assertNotNull(one);
    }

    @Test
    void testListByMap() {
        Map<String, Object> map = new HashMap<>();
        map.put("id", 1L);
        List<Entity> list = Db.listByMap(map, Entity.class);
        Assertions.assertEquals(1, list.size());
        Assertions.assertEquals("ruben", list.get(0).getName());
    }

    @Test
    void testByIds() {
        List<Entity> list = Db.listByIds(Arrays.asList(1L, 2L), Entity.class);
        Assertions.assertEquals(2, list.size());
    }

    @Test
    void testGetMap() {
        Map<String, Object> map = Db.getMap(Wrappers.lambdaQuery(Entity.class));
        Assertions.assertNotNull(map);

        Entity entity = new Entity();
        entity.setId(1L);
        map = Db.getMap(entity);
        Assertions.assertNotNull(map);
    }

    @Test
    void testList() {
        List<Entity> list = Db.list(Wrappers.lambdaQuery(Entity.class));
        Assertions.assertEquals(2, list.size());

        list = Db.list(Entity.class);
        Assertions.assertEquals(2, list.size());

        Entity entity = new Entity();
        entity.setId(1L);
        list = Db.list(entity);
        Assertions.assertEquals(1, list.size());
    }

    @Test
    void testListMaps() {
        List<Map<String, Object>> list = Db.listMaps(Wrappers.lambdaQuery(Entity.class));
        Assertions.assertEquals(2, list.size());

        list = Db.listMaps(Entity.class);
        Assertions.assertEquals(2, list.size());

        Entity entity = new Entity();
        entity.setId(1L);
        list = Db.listMaps(entity);
        Assertions.assertEquals(1, list.size());
    }

    @Test
    void testListObjs() {
        List<Entity> list = Db.listObjs(Entity.class);
        Assertions.assertEquals(2, list.size());

        List<Long> objectList = Db.listObjs(Wrappers.lambdaQuery(Entity.class), Entity::getId);
        Assertions.assertEquals(2, objectList.size());

        List<String> names = Db.listObjs(Entity.class, Entity::getName);
        Assertions.assertArrayEquals(new String[]{"ruben", "chocolate"}, names.toArray());
    }

    @Override
    protected List<Interceptor> interceptors() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.SQLITE));
        return Collections.singletonList(interceptor);
    }

    @Test
    void testPageMaps() {
        Page<Map<String, Object>> page = Db.pageMaps(new Page<>(1, 1), Entity.class);
        Assertions.assertEquals(2, page.getTotal());

        page = Db.pageMaps(new Page<>(1, 1), Wrappers.lambdaQuery(Entity.class));
        Assertions.assertEquals(1, page.getRecords().size());
    }

    @Test
    void testPage() {
        IPage<Entity> page = Db.page(new Page<>(1, 1), Entity.class);
        Assertions.assertEquals(2, page.getTotal());
        page = Db.page(new Page<>(1, 1), Wrappers.lambdaQuery(Entity.class));
        Assertions.assertEquals(1, page.getRecords().size());
    }

    @Test
    void testChain() {
        QueryChainWrapper<Entity> query = Db.query(Entity.class);
        List<Entity> list = query.eq("id", 1L).list();
        Assertions.assertEquals(1, list.size());

        LambdaQueryChainWrapper<Entity> lambdaQuery = Db.lambdaQuery(Entity.class);
        list = lambdaQuery.eq(Entity::getId, 1L).list();
        Assertions.assertEquals(1, list.size());

        UpdateChainWrapper<Entity> update = Db.update(Entity.class);
        update.eq("id", 1L).set("name", "bee bee I'm a sheep").update();
        Assertions.assertEquals("bee bee I'm a sheep", lambdaQuery.eq(Entity::getId, 1L).one().getName());

        LambdaUpdateChainWrapper<Entity> lambdaUpdate = Db.lambdaUpdate(Entity.class);
        lambdaUpdate.eq(Entity::getId, 1L).set(Entity::getName, "be better").update();
        Assertions.assertEquals("be better", lambdaQuery.eq(Entity::getId, 1L).one().getName());
    }

    @Test
    void testGetObj() {
        String name = Db.getObj(Wrappers.lambdaQuery(Entity.class).eq(Entity::getId, 1L), Entity::getName);
        Assertions.assertEquals("ruben", name);
    }


    @Override
    protected String tableDataSql() {
        return "insert into entity(id,name) values(1,'ruben'),(2,'chocolate');";
    }

    @Override
    protected List<String> tableSql() {
        return Arrays.asList("drop table if exists entity", "CREATE TABLE IF NOT EXISTS entity (" +
            "id BIGINT NOT NULL," +
            "name VARCHAR(30) NULL DEFAULT NULL," +
            "PRIMARY KEY (id))");
    }
}

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值