新手學(xué)做網(wǎng)站要花錢么大數(shù)據(jù)營銷推廣精準(zhǔn)粉
文章目錄
- 情景
- 查詢一個實體類對象
- 查詢一個List集合
- 查詢單個數(shù)據(jù)
- 查詢一條數(shù)據(jù)為map集合
- 查詢多條數(shù)據(jù)為map集合
- 方法一
- 方法二
情景
- 如果查詢出的數(shù)據(jù)只有一條,可以通過
- 實體類對象接收
- List集合接收
- Map集合接收,結(jié)果
{password=123456, sex=男, id=1, age=23, username=admin}
- 如果查詢出的數(shù)據(jù)有多條,一定不能用實體類對象接收,會拋異常TooManyResultsException,可以通過
- 實體類類型的LIst集合接收
- Map類型的LIst集合接收
- 在mapper接口的方法上添加@MapKey注解
查詢一個實體類對象
/*** 根據(jù)用戶id查詢用戶信息* @param id* @return*/
User getUserById(@Param("id") int id);
<!--User getUserById(@Param("id") int id);-->
<select id="getUserById" resultType="User">select * from t_user where id = #{id}
</select>
查詢一個List集合
/*** 查詢所有用戶信息* @return*/
List<User> getUserList();
<!--List<User> getUserList();-->
<select id="getUserList" resultType="User">select * from t_user
</select>
查詢單個數(shù)據(jù)
/** * 查詢用戶的總記錄數(shù) * @return * 在MyBatis中,對于Java中常用的類型都設(shè)置了類型別名 * 例如:java.lang.Integer-->int|integer * 例如:int-->_int|_integer * 例如:Map-->map,List-->list */
int getCount();
<!--int getCount();-->
<select id="getCount" resultType="_integer">select count(id) from t_user
</select>
查詢一條數(shù)據(jù)為map集合
/** * 根據(jù)用戶id查詢用戶信息為map集合 * @param id * @return */
Map<String, Object> getUserToMap(@Param("id") int id);
<!--Map<String, Object> getUserToMap(@Param("id") int id);-->
<select id="getUserToMap" resultType="map">select * from t_user where id = #{id}
</select>
<!--結(jié)果:{password=123456, sex=男, id=1, age=23, username=admin}-->
查詢多條數(shù)據(jù)為map集合
方法一
/** * 查詢所有用戶信息為map集合 * @return * 將表中的數(shù)據(jù)以map集合的方式查詢,一條數(shù)據(jù)對應(yīng)一個map;若有多條數(shù)據(jù),就會產(chǎn)生多個map集合,此時可以將這些map放在一個list集合中獲取 */
List<Map<String, Object>> getAllUserToMap();
<!--Map<String, Object> getAllUserToMap();-->
<select id="getAllUserToMap" resultType="map"> select * from t_user
</select>
<!--結(jié)果:[{password=123456, sex=男, id=1, age=23, username=admin},{password=123456, sex=男, id=2, age=23, username=張三},{password=123456, sex=男, id=3, age=23, username=張三}]
-->
方法二
/*** 查詢所有用戶信息為map集合* @return* 將表中的數(shù)據(jù)以map集合的方式查詢,一條數(shù)據(jù)對應(yīng)一個map;若有多條數(shù)據(jù),就會產(chǎn)生多個map集合,并且最終要以一個map的方式返回數(shù)據(jù),此時需要通過@MapKey注解設(shè)置map集合的鍵,值是每條數(shù)據(jù)所對應(yīng)的map集合*/
@MapKey("id")
Map<String, Object> getAllUserToMap();
<!--Map<String, Object> getAllUserToMap();-->
<select id="getAllUserToMap" resultType="map">select * from t_user
</select>
<!--結(jié)果:{1={password=123456, sex=男, id=1, age=23, username=admin},2={password=123456, sex=男, id=2, age=23, username=張三},3={password=123456, sex=男, id=3, age=23, username=張三}}
-->