[MyBatis]查询语句的返回listmap

xiaoxiao2021-02-28  57

List

public List getPersonByLikeName(@Param("p_Name") String name); <!--返回值类型为List, mybatis会自动封装, 【resultType】还是写list里的实体类类型而不是写list--> <select id="getPersonByLikeName" resultType="com.yiki.Entity.Person"> select * from Person where p_name like #{p_Name} </select>

测试类

public void selectReturnList() throws IOException { start(); PersonMapper mapper = sqlSession.getMapper(PersonMapper.class); List list = mapper.getPersonByLikeName("%t%");//名字里带e字母的 System.out.println(list.toString()); sqlSession.close(); log.debug("test"); }

Map

单条记录

public Map<String,Object> getPersonByIdReturnMap(@Param("id") Integer id); <!--返回值为map:<列名+对应值> map是框架起的别名 --> <select id="getPersonByIdReturnMap" resultType="map"> select * from Person where pid = #{id} </select> public void selectReturnMap() throws IOException { start(); PersonMapper mapper = sqlSession.getMapper(PersonMapper.class); Map map = mapper.getPersonByIdReturnMap(1); System.out.println(map); //key value //id 1 //p_name tiffany System.out.println(map.get("pid")); sqlSession.close(); log.debug("test"); }

多条记录

需要知道map的key是什么东西,如指定为主键或其他列名

@MapKey("pId") public Map<Integer,Person> getPersonByIdReturnMutipleMap(@Param("p_Name") String name); <!--返回多条map 返回值为<Integer,Person> 对应 主键+对象 【resultType】还是写map里的实体类类型而不是写map --> <select id="getPersonByIdReturnMutipleMap" resultType="com.yiki.Entity.Person"> select * from Person where p_name like #{p_Name} </select> public void selectReturnMutipleMap() throws IOException { start(); PersonMapper mapper = sqlSession.getMapper(PersonMapper.class); Map map = mapper.getPersonByIdReturnMutipleMap("tiffany"); System.out.println(map); //key value //1 person1 //2 person2 System.out.println(map.get(1)); sqlSession.close(); log.debug("test"); }

转载请注明原文地址: https://www.6miu.com/read-2627223.html

最新回复(0)