您的位置:首页 > 其它

mybatis selectMap方法使用注意事项

2017-02-04 17:13 555 查看
mybatis selectMap方法返回指定列为key的map集合或对象,它的value值得类型可以为Object或map,在不绑定bean下默认为Map<String,String>类型,即以对象的属性名作为key,注意都是key和value都是String类型,

形式是

Map<String, Map<String,String>>


, 绑定实体bean,则形式例如以下形式:
Map<String, User>


selectMap方法的第三个参数为指定map key的列名。

在mybatis定义select的返回结果类型是map类型时,

<select id="getResult" parameterType="map" resultType="map">
select id,username from user where id=#{id}
</select>


dao类调用

返回一个对象的情况:

publicMap<String, Map<String,String>>getResult(Map params) {
return this.sqlSessionTemplate.selectMap("getResult", params, "id");
}


返回集合的情况:

public List<Map<String, Map<String,String>>> getResult(Map params) {
return this.sqlSessionTemplate.selectMap("getResult", params, "id");
}


id是Long类型,则如果定义了Map<String,Map<String,String>>变量来接的时候,是不是能通过get("123")这样能能否获取到当前的记录的Object了?

假如user表有一条数据id为123

Map<String, Map<String,String>> result=getResult(paramMap);

result.get("123");//获取到的记录为null

result.get(123);//能获取到记录


为什么result.get("123");获取不到数据了,明明我定义了Map<String, Object>类型的变量来接,它应该会强转呀,我告诉你Map不存在强转这么一说,

你如果用Map<Integer,Object>去转换Map<String,Object>,程序会报错的,不能转换。那为什么这里程序没有报错了?

请看下面的mybatis selectMap模拟实现代码:

import java.util.HashMap;
import java.util.Map;

public class TestSqlSession {
public static void main(String[] args) {
TestSqlSession sqlSession=new TestSqlSession();
Map<String,Map<String,String>> hashMap=sqlSession.selectMap();
String strKey="12345612";
Integer intKey=12345612;
System.out.println(hashMap.containsKey(strKey));//返回false
System.out.println(hashMap.containsKey(intKey));//返回true
Map<String,String> user=hashMap.get(intKey);
System.out.println(user.get("id"));//12345612
System.out.println(user.get("name"));//denghuafeng
}
@SuppressWarnings("unchecked")
public  <K, V> Map<K, V> selectMap(){
Map<K, V> hashMap=new HashMap<K, V>();
Object key=12345612;
Object value=null;
Map<String,String> map=new HashMap<String,String>();
map.put("id", key.toString());
map.put("name", "denghuafeng");
value=map;
K k=(K)key;
V v=(V)value;
hashMap.put(k, v);
return hashMap;
}
}


mybatis selctMap的方法获取的key是什么类型则是什么类型,由于我们resultType指定的是Map,则id的数据类型则交由mybatis去判断处理了,所以导致结果不是想要的结果,那应该怎样解决了?

resultMap指定明确的绑定pojo对象的map,这样的返回的结果,pojo的id是什么类型,则key就是什么类型。比如pojo的定义的id属性的数据类型是String类型,则上面dao的返回类型可不用改,如果是Long类型,则需改成Map<Long,Object>。

改成代码如下这样:

<resultMap id="get-user-result" type="com.denghuafeng.User">
<result property="id" column="id"/>
<result property="username" column="username"/>
</resultMap>

<select id="getResult" parameterType="map" resultType="get-user-result">
select id,username from user where id=#{id}
</select>


如果绑定了User bean,则可以这样:

publicMap<String, User> getResult(Map params) {
return this.sqlSessionTemplate.selectMap("getResult", params, "id");
}

//返回集合的情况:

public List<Map<String, User> getResult(Map params) {
return this.sqlSessionTemplate.selectMap("getResult", params, "id");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: