您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
本篇内容主要讲解“Mybatis如何返回Map数据”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Mybatis如何返回Map数据”吧!
public interface UserMapper { List<Map<String, String>> selectTestData1(); }
<?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="xxx.mapper.UserMapper"> <select id="selectTestData1" resultType="java.util.Map"> SELECT t_user.id as id, t_user.email as email, t_user.avatar as avatar FROM t_user </select> </mapper>
@Service public class MapTest implements CommandLineRunner { @Autowired private UserMapper mapper; @Override public void run(String... args) throws Exception { List<Map<String, String>> listData1 = mapper.selectTestData1(); for (Map<String, String> map : listData1) { System.out.println(map); } } }
import org.apache.ibatis.annotations.MapKey; public interface UserMapper { // 指定的key必须是唯一的,否则重复的重复map的key会覆盖,如果查询的字段中没有唯一值,可以通过rowno来指定 @MapKey("rowno") Map<String, Map<String,String>> selectTestData2(); }
<?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="xxx.mapper.UserMapper"> <!-- ❗❗❗由于mysql没有oracle中的ROWNUM功能,因此只能通过下面的方式进行模拟 --> <select id="selectTestData2" resultType="java.util.Map"> SELECT @rowno := @rowno + 1 AS rowno, t_user.email AS email, t_user.avatar AS avatar FROM t_user, ( SELECT @rowno := 0 ) t ORDER BY rowno DESC </select> </mapper>
@Service public class MapTest implements CommandLineRunner { @Autowired private UserMapper mapper; @Override public void run(String... args) throws Exception { Map<String, Map<String, String>> mapData1 = mapper.selectTestData2(); System.out.println(mapData1); } }
import org.apache.ibatis.annotations.MapKey; public interface UserMapper { // 指定的key名称必须是User实体类中的属性 @MapKey("id") Map<String, User> selectTestData3(); }
<?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="xxx.mapper.UserMapper"> <!--由于最终是把数据封装到User实体类中,所以返回值的数据类型是User而不是Map--> <select id="selectTestData3" resultType="com.example.demo.transactionCom.entity.User"> SELECT t_user.id as id, t_user.email as email, t_user.avatar as avatar FROM t_user </select> </mapper>
@Service public class MapTest implements CommandLineRunner { @Autowired private UserMapper mapper; @Override public void run(String... args) throws Exception { Map<String, User> mapData2 = mapper.selectTestData3(); Set<Map.Entry<String, User>> entries = mapData2.entrySet(); for (Map.Entry<String, User> entry : entries) { User user = entry.getValue(); System.out.println(user); } } }
到此,相信大家对“Mybatis如何返回Map数据”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。