Mybatis各种查询功能
常规返回结果集
-
List
-
mybatis默认别名已经设置了 List
- 结果集依然要保留对应对象类型,mybatis会自动封装,发现有多条时,会自动封装成 List 集合
-
// .xml中: <select id="select" resultType="User"> select * from user where password = #{password} and username=#{username}; </select> //自动形成List<User>的集合后返回!
-
-
Map(重点)
-
Mybatis默认别名已经设置了 Map
-
若返回是 多个Map, 采用List< Map > 集合。
// java中: List<User> select(String passWord,String userName){ ... mapper = sqlSessin.getMapper(..); Map<String,Object> = mapper.select(); // .xml中:返回单个 <select id="select" resultType="map"> select * from user where password = #{password} and username=#{username}; </select> // 会自动封装一个相应键值对为map的集合
-
若返回是 多个Map, 采用List< Map > 集合。
-
// java中: List<User> select(String passWord,String userName){ ... mapper = sqlSessin.getMapper(..); List<Map<String,Object>> = mapper.select () } // .xml中:返回多个类型 <select id="select" resultType="map"> select * from user; </select> // 会自动封装一个相应键值对为map的list集合
-
-
@MapKey
-
若想用某一列作key,则可以使用@Mapkey,自定义Key
// java中: List<User> select(String passWord,String userName){ ... mapper = sqlSessin.getMapper(..); @MapKey("id") Map<String,Object> = mapper.select () //注意 这里用的是Object类型 但是特地的User对象 只要符合,也可以 } // .xml中:返回多个类型 <select id="select" resultType="map"> select id, username, password from user; </select> // 会自动封装一个key = id 的map集合 //结果如下:(key在前面,值在后面) map = { 1,{id = 1,username = 张三,password = 123}, 2,{id = 2,username = 张三,password = 456}, 3,{id = 3,username = 李四,password = 789}, }
-
但是需要注意!请以唯一标识作为Key!不然会被覆盖!举个例子
// java中: List<User> select(String passWord,String userName){ ... mapper = sqlSessin.getMapper(..); @MapKey("username") Map<String,Object> = mapper.select () } // .xml中:返回多个类型 <select id="select" resultType="map"> select id, username, password from user; </select> // 会自动封装一个key = id 的map集合 //结果如下:(key在前面,值在后面) map = { 张三, {id = 2,username = 张三,password = 123}, 李四, {id = 3,username = 李四,password = 789}, } // !!! 很显然 id = 1 的 张三 被 覆盖了
-
-
-
模糊返回结果集
-
(最常用) 利用 **“%” #{ } “%” ** 方式
-
// java中: List<User> select(int ID){ ... mapper = sqlSessin.getMapper(..); User user = mapper.select (@Param("id") ID) } // .xml中 <select id="select" resultType="user"> select * from user where id = "%"#{id}"%"; </select> // 都是可以的 <select id="select" resultType="user"> select * from user where id = "."#{id}"%"; </select>
-