mybatislectMap⽅法使⽤注意事项
mybatis lectMap⽅法返回指定列为key的map集合或对象,它的value值得类型可以为Object或map,在不绑定bean下默认为
Map<String,String>类型,即以对象的属性名作为key,注意都是key和value都是String类型,
形式是
Map<String, Map<String,String>>餐巾纸的英文
, 绑定实体bean,则形式例如以下形式:
Map<String, Ur>
。
lectMap⽅法的第三个参数为指定map key的列名。
在mybatis定义lect的返回结果类型是map类型时,
<lect id="getResult" parameterType="map" resultType="map">
lect id,urname from ur where id=#{id}
</lect>
dao类调⽤
返回⼀个对象的情况:
public Map<String, Map<String,String>> getResult(Map params) {
return this.sqlSessionTemplate.lectMap("getResult", params, "id");
}
返回集合的情况:
public List<Map<String, Map<String,String>>> getResult(Map params) {
return this.sqlSessionTemplate.lectMap("getResult", params, "id");
}
id是Long类型,则如果定义了Map<String,Map<String,String>>变量来接的时候,是不是能通过get("123")这样能能否获取到当前的记录的Object了?
肃然起敬
平凡中坚守假如ur表有⼀条数据id为123
Map<String, Map<String,String>> result=getResult(paramMap);
<("123");//获取到的记录为null
<(123);//能获取到记录
为什么("123");获取不到数据了,明明我定义了Map<String, Object>类型的变量来接,它应该会强转呀,我告诉你Map不存在强转这么⼀说,
你如果⽤Map<Integer,Object>去转换Map<String,Object>,程序会报错的,不能转换。那为什么这⾥程序没有报错了?
请看下⾯的mybatis lectMap模拟实现代码:
import java.util.HashMap;
二年级数学应用题100道>前半生演员表
import java.util.Map;
public class TestSqlSession {
public static void main(String[] args) {
TestSqlSession sqlSession=new TestSqlSession();
Map<String,Map<String,String>> hashMap=sqlSession.lectMap();
String strKey="12345612";
Integer intKey=12345612;
System.out.ainsKey(strKey));//返回fal
System.out.ainsKey(intKey));//返回true
Map<String,String> (intKey);
System.out.("id"));//12345612
System.out.("name"));//denghuafeng健身气功易筋经
}
@SuppressWarnings("unchecked")
public <K, V> Map<K, V> lectMap(){
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", String());
map.put("name", "denghuafeng");国有五大银行
value=map;
什么遥望
K k=(K)key;
V v=(V)value;
hashMap.put(k, v);
return hashMap;
}
}
mybatis lctMap的⽅法获取的key是什么类型则是什么类型,由于我们resultType指定的是Map,则id的数据类型则交由mybatis去判断处理了,所以导致结果不是想要的结果,那应该怎样解决了?
resultMap指定明确的绑定pojo对象的map,这样的返回的结果,pojo的id是什么类型,则key就是什么类型。⽐如pojo的定义的id属性的数据类型是String类型,则上⾯dao的返回类型可不⽤改,如果是Long类型,则需改成Map<Long,Object>。
改成代码如下这样:
<resultMap id="get-ur-result" type="com.denghuafeng.Ur">
<result property="id" column="id"/>
<result property="urname" column="urname"/>
</resultMap>
<lect id="getResult" parameterType="map" resultType="get-ur-result">
lect id,urname from ur where id=#{id}
</lect>
如果绑定了Ur bean,则可以这样:
public Map<String, Ur> getResult(Map params) {
return this.sqlSessionTemplate.lectMap("getResult", params, "id"); }
//返回集合的情况:
public List<Map<String, Ur> getResult(Map params) {
return this.sqlSessionTemplate.lectMap("getResult", params, "id"); }