您好,登錄后才能下訂單哦!
本篇內容主要講解“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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。