最近在研读Mybaits 3.2.6的源码,发现设计的一个缺陷,欢迎拍砖交流
在SqlSession接口中,有这样一个方法:
/**
* The selectMap is a special case in that it is designed to convert a list
* of results into a Map based on one of the properties in the resulting
* objects.
* @param <K> the returned Map keys type
* @param <V> the returned Map values type
* @param statement Unique identifier matching the statement to use.
* @param parameter A parameter object to pass to the statement.
* @param mapKey The property to use as key for each value in the list.
* @return Map containing key pair data.
*/
<K, V> Map<K, V> selectMap(String statement, Object parameter, String mapKey);
这个方法的翻译是查询返回Map,参数含义依次为语句id,参数对象,结果集的作为key的属性列名。
缺陷就在于mapKey,mapKey要标识每一行记录,大家第一想到就是表id了,id一般都不是数字,而Mybaits偏偏给你定义为字符串,太扯蛋了吧。另外,如果有复合主键的情况,也是有问题的。
所以id不能作为mapKey参数使用。因此这个方法实际上没用,无法使用!
改进的思路,将mapKey设置为String类型不变,而在填充Map结果集时候,进行包装即可,如果是数字,则使用StringValueOf(rs.getLong(mapKey))进行转换,或者直接rs.getString(mapKey),也可以搞定。
这样这个方法就强大很多了。
当然复合主键的问题还是不能解决,我觉得复合主键是表设计很矬的问题,不予理睬。
如果真想解决,mapKey可以通过约定,将多个列名用逗号分隔,比如 “code,key”,接收到参数后对参数进行分解,分别获取两个列名,然后分别getString("code")+getString("key")作为主键,也可以解决。
期待作者早日修正,则个文档也很矬,查询返回map竟然大批人在百度上问,没一个把mapKey含义说清楚的!
本文出自 “熔 岩” 博客,请务必保留此出处http://lavasoft.blog.51cto.com/62575/1384984
Mybaits 3.2.6设计的一个缺陷,欢迎拍砖交流,布布扣,bubuko.com
原文:http://lavasoft.blog.51cto.com/62575/1384984