MyBatis的各种查询功能

MyBatis的各种查询功能

1、查询一个实体类对象

接口:

/**
* 根据用户id查询用户信息 * @param id
* @return
*/
User getUserById(@Param("id") int id);

xml:

<!--User getUserById(@Param("id") int id);-->
<select id="getUserById" resultType="User">
    select * from t_user where id = #{id}
</select>

2、查询一个list集合

接口:

/**
* 查询所有用户信息 * @return
*/
List<User> getUserList();

xml:

<!--List<User> getUserList();-->
<select id="getUserList" resultType="User">
    select * from t_user
</select>

3、查询单个数据

接口:

/**
* 查询用户的总记录数
* @return
* 在MyBatis中,对于Java中常用的类型都设置了类型别名 * 例如: java.lang.Integer-->int|integer
* 例如: int-->_int|_integer
* 例如: Map-->map,List-->list
*/
int getCount();

xml:

<!--int getCount();-->
<select id="getCount" resultType="_integer">
    select count(id) from t_user
</select>

4、查询一条数据为map集合

接口:

/**
* 根据用户id查询用户信息为map集合 * @param id
* @return
*/
Map<String, Object> getUserToMap(@Param("id") int id);

xml:

<!--Map<String, Object> getUserToMap(@Param("id") int id);--> 
<!--结果: {password=123456, sex=男 , id=1, age=23, username=admin}--> 
<select id="getUserToMap" resultType="map">
    select * from t_user where id = #{id}
</select>

5、查询多条数据为map集合

5.1、方式一

接口:

/**
* 查询所有用户信息为map集合
* @return
* 将表中的数据以map集合的方式查询,一条数据对应一个map;
* 若有多条数据,就会产生多个map集合,此时可以将这些map放在一个list集合中获取
*/
List<Map<String, Object>> getAllUserToMap();

xml:

<!--Map<String, Object> getAllUserToMap();-->
<select id="getAllUserToMap" resultType="map">
    select * from t_user
</select>
5.2、方式二

接口:

/**
* 查询所有用户信息为map集合
* @return
* 将表中的数据以map集合的方式查询,一条数据对应一个map;
* 若有多条数据,就会产生多个map集合,并且最终要以一个map的方式返回数据,
* 此时需要通过@MapKey注解设置map集合的键,值是每条数据所对应的 map集合
*/
@MapKey("id")
Map<String, Object> getAllUserToMap();

xml:

<!--Map<String, Object> getAllUserToMap();-->
<!--
{
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=张三}
}
-->
<select id="getAllUserToMap" resultType="map">
    select * from t_user
</select>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值