当前位置: 代码网 > it编程>编程语言>Java > Mybatis返回Map对象的实现

Mybatis返回Map对象的实现

2024年09月23日 Java 我要评论
一、场景介绍假设有如下一张学生表:create table `student` ( `id` int not null auto_increment comment '主键', `name` va

一、场景介绍

假设有如下一张学生表:

create table `student` (
  `id` int not null auto_increment comment '主键',
  `name` varchar(100) not null comment '姓名',
  `gender` varchar(10) not null comment '性别',
  `grade` int not null comment '年级',
  primary key (`id`)
) engine=innodb comment='学生信息表';

我们通过一组 ids,想获得 id 跟学生对象的映射 map<integer, student>,可以这样做:

1、先通过 ids 获取对象列表

2、再通过 stream 流式运算得到 id-student 映射

这样做虽然也没有问题,但是这样 service 层就会散落一堆这样流式运算的代码。不是很美观,应该在dao层就提供这种能力。mybatis 提供给我们查询 map 的方式。

@service
public class studentserviceimpl implements studentservice {

    @autowired
    private studentmapper mapper;

    @override
    public map<integer, student> findmapbyids(list<integer> ids) {
        list<student> students = mapper.listbyids(ids);
        map<integer, student> map = students.stream().collect(collectors.tomap(student::getid, function.identity()));
        return map;
    }
}
---------------------------------------------------------------
@test
public void test() {
        list<integer> list = arrays.aslist(1,2,3);
        map<integer, student> map = studentservice.findmapbyids(list);
        system.out.println(map);
}

输出:
{1=student(id=1, name=小明, gender=male, grade=1), 2=student(id=2, name=小红, gender=female, grade=2), 3=student(id=3, name=小李, gender=male, grade=3)}

二、mybatis @mapkey 方式

mybatis 提供了 @mapkey 注解,注解的 value 用来指定 key 的取值字段。

可以看到,效果是一样的。

@mapper
public interface studentmapper {

    /**
     * 这种基础的查询,不应该先获取 list 流,然后再转换,
     * 这样会使整个项目散落一地这种代码
     * 应该在dao层就提供这种能力
     */
    @mapkey("id")
    map<integer, student> findmapbyids(list<integer> ids);
}
-------------------------------------------------------------
<?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.study.student.mapper.studentmapper">
    
    <select id="findmapbyids" resulttype="com.study.student.entity.student">
        select *
        from student s
        <where>
            and s.id in
            <foreach collection="ids" item="id" open="(" separator="," close=")">
                #{id}
            </foreach>
        </where>
    </select>

</mapper>
-------------------------------------------------------------
@service
public class studentserviceimpl implements studentservice {

    @autowired
    private studentmapper mapper;

    @override
    public map<integer, student> findmapbyids(list<integer> ids) {
        /*
        list<student> students = mapper.listbyids(ids);
        map<integer, student> map = students.stream().collect(collectors.tomap(student::getid, function.identity()));
        return map;
        */
        return mapper.findmapbyids(ids);
    }
}
-------------------------------------------------------------
@test
public void test() {
        list<integer> list = arrays.aslist(1,2,3);
        map<integer, student> map = studentservice.findmapbyids(list);
        system.out.println(map);
}
输出:
{1=student(id=1, name=小明, gender=male, grade=1), 2=student(id=2, name=小红, gender=female, grade=2), 3=student(id=3, name=小李, gender=male, grade=3)}

 但如果 @mapkey 的 value 配置了记录重复的字段会怎么样?

就比如,@mapkey("grade"),grade = 1,2,3 的记录并非唯一。

@mapper
public interface studentmapper {

    list<student> listbyids(list<integer> ids);

    /**
     * @mapkey 的 value 是 grade 这种非唯一字段
     */
    @mapkey("grade")
    map<integer, student> findmapbyids(list<integer> ids);
}

 这个时候会发现,返回的记录被覆盖了。

id in [1,6] 的 grade=1 的记录有 小明跟小智,

小明先查询出来,

map.put(1,  student(id=1, name=小明, gender=male, grade=1))

小智后查询出来,

map.put(1,  student(id=6, name=小智, gender=male, grade=1))

同一个key,小智覆盖了小明。

那如果我们希望返回 map<grade:integer, list<student>> 怎么办呢?

@test
public void test2() {
        list<integer> list = arrays.aslist(1,2,3,4,5,6);
        map<integer, student> map = studentservice.findmapbyids(list);
        system.out.println(map);
}
输出:
{1=student(id=6, name=小智, gender=male, grade=1), 2=student(id=4, name=小林, gender=male, grade=2), 3=student(id=5, name=小婷, gender=female, grade=3)}

三、stream 返回 map<integer, list<student>>

 遗憾的是,笔者找了 mybatis 跟 mybatisplus 也没找到此类方法,所以这一块,还是只能用流式计算来做。

@mapper
public interface studentmapper {

    list<student> listbyids(list<integer> ids);
}
-------------------------------------------------------------
<?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.study.student.mapper.studentmapper">
    
    <select id="listbyids" resulttype="cn.al.admin.entity.finance.student">
        select *
        from student s
        <where>
            and s.id in
            <foreach collection="ids" item="id" open="(" separator="," close=")">
                #{id}
            </foreach>
        </where>
    </select>

</mapper>
-------------------------------------------------------------
@service
public class studentserviceimpl implements studentservice {

    @autowired
    private studentmapper mapper;

    @override
    public map<integer, list<student>> getmapbyids(list<integer> ids) {
        list<student> students = mapper.listbyids(ids);
        return students.stream().collect(collectors.groupingby(student::getgrade));
    }
}
-------------------------------------------------------------
@test
public void test3() {
        list<integer> list = arrays.aslist(1,2,3,4,5,6);
        map<integer, list<student>> map = studentservice.getmapbyids(list);
        system.out.println(map);
    }
输出:
{1=[student(id=1, name=小明, gender=male, grade=1), student(id=6, name=小智, gender=male, grade=1)], 2=[student(id=2, name=小红, gender=female, grade=2), student(id=4, name=小林, gender=male, grade=2)], 3=[student(id=3, name=小李, gender=male, grade=3), student(id=5, name=小婷, gender=female, grade=3)]}

四、mybatisplus 返回 list<map<string, object>>

如果希望查询返回 list<map<string, object>> map 的 key 是数据库 column name

package com.study.student.mapper;

import com.study.student.entity.student;
import com.baomidou.mybatisplus.core.mapper.basemapper;
import org.apache.ibatis.annotations.*;

@mapper
public interface studentmapper extends basemapper<student> {
}
------------------------------------------------------------
package com.study.student.service.impl;

import com.study.student.entity.student;
import com.study.student.mapper.studentmapper;
import com.study.student.service.studentservice;
import com.baomidou.mybatisplus.core.conditions.query.lambdaquerywrapper;
import com.baomidou.mybatisplus.extension.service.impl.serviceimpl;
import org.springframework.stereotype.service;

import java.util.list;
import java.util.map;

@service
public class studentserviceimpl extends serviceimpl<studentmapper, student> implements studentservice {

    @override
    public list<map<string, object>> getmaplist(list<integer> ids) {
        lambdaquerywrapper<student> wrapper = new lambdaquerywrapper<>();
        wrapper.in(student::getid, ids);
        return this.getbasemapper().selectmaps(wrapper);
    }
}
------------------------------------------------------------
@test
public void test4() {
        list<integer> list = arrays.aslist(1,2,3,4,5,6);
        list<map<string, object>> map = studentservice.getmaplist(list);
        system.out.println(map);
}
输出:
[{gender=male, grade=1, name=小明, id=1, photo_url=url1}, {gender=female, grade=2, name=小红, id=2, photo_url=url2}, {gender=male, grade=3, name=小李, id=3, photo_url=url3}, {gender=male, grade=2, name=小林, id=4, photo_url=url4}, {gender=female, grade=3, name=小婷, id=5, photo_url=url5}, {gender=male, grade=1, name=小智, id=6, photo_url=url6}]

五、json 返回  list<map<string, object>>

如果希望查询返回 list<map<string, object>> map 的 key 是对象 property。需要借助 json 工具类,比如 cn.hutool.core.bean.beanutil#beantomap

package com.study.student.service.impl;

import com.study.student.entity.student;
import com.study.student.mapper.studentmapper;
import com.study.student.service.studentservice;
import com.baomidou.mybatisplus.core.conditions.query.lambdaquerywrapper;
import com.baomidou.mybatisplus.extension.service.impl.serviceimpl;
import org.springframework.stereotype.service;

import cn.hutool.core.bean.beanutil;

import java.util.list;
import java.util.map;

@service
public class studentserviceimpl extends serviceimpl<studentmapper, student> implements studentservice {

    @override
    public list<map<string, object>> getmaplist(list<integer> ids) {
        list<student> students = this.listbyids(ids);
        return students.stream().map(beanutil::beantomap).collect(collectors.tolist());
    }
}
------------------------------------------------------------
@test
public void test5() {
        list<integer> list = arrays.aslist(1,2,3,4,5,6);
        list<map<string, object>> map = studentservice.getmaplist(list);
        system.out.println(map);
}
输出:
[{id=1, name=小明, gender=male, grade=1, photourl=url1}, {id=2, name=小红, gender=female, grade=2, photourl=url2}, {id=3, name=小李, gender=male, grade=3, photourl=url3}, {id=4, name=小林, gender=male, grade=2, photourl=url4}, {id=5, name=小婷, gender=female, grade=3, photourl=url5}, {id=6, name=小智, gender=male, grade=1, photourl=url6}]

六、mybatisplus 返回 map<string, object>

map 的 key 是数据库 column name

package com.study.student.service.impl;

import com.study.student.entity.student;
import com.study.student.mapper.studentmapper;
import com.study.student.service.studentservice;
import com.baomidou.mybatisplus.core.conditions.query.lambdaquerywrapper;
import com.baomidou.mybatisplus.extension.service.impl.serviceimpl;
import org.springframework.stereotype.service;

import java.util.list;
import java.util.map;

@service
public class studentserviceimpl extends serviceimpl<studentmapper, student> implements studentservice {

    @override
    public map<string, object> getmapbyid(integer id) {
        lambdaquerywrapper<student> wrapper = new lambdaquerywrapper<>();
        wrapper.eq(student::getid, id);
        return this.getmap(wrapper);
    }
}
------------------------------------------------------------
@test
public void test6() {
        map<string, object> map = studentservice.getmapbyid(6);
        system.out.println(map);
    }
输出:
{gender=male, grade=1, name=小智, id=6, photo_url=url6}

七、json 返回 map<string, object>

map 的 key 是对象 property

package com.study.student.service.impl;

import com.study.student.entity.student;
import com.study.student.mapper.studentmapper;
import com.study.student.service.studentservice;
import com.baomidou.mybatisplus.core.conditions.query.lambdaquerywrapper;
import com.baomidou.mybatisplus.extension.service.impl.serviceimpl;
import org.springframework.stereotype.service;

import cn.hutool.core.bean.beanutil;

import java.util.list;
import java.util.map;

@service
public class studentserviceimpl extends serviceimpl<studentmapper, student> implements studentservice {

    @override
    public map<string, object> getmapbyid(integer id) {
        student student = this.getbyid(id);
        return beanutil.beantomap(student);
    }
}
------------------------------------------------------------
@test
public void test7() {
    map<string, object> map = studentservice.getmapbyid(6);
    system.out.println(map);
}
输出:
{id=6, name=小智, gender=male, grade=1, photourl=url6}

到此这篇关于mybatis返回map对象的实现的文章就介绍到这了,更多相关mybatis返回map对象内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网! 

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com