Mybatis查询结果为两列时,结果保存为key-value的map mybatis查询结果为map时,出来的结果默认是下⾯这样的
[{
key: 1,
value: 'xx'
},
{
key: 2,
value: 'xxx'
}]
我们想要的是这样的:
{
1 : 'xx',
2 : 'xxx'
}
nation和nationality的区别如果⾃⼰转换的话⾮常⿇烦。经过⼀番查,发现mybatis可以在查询出来的时候通过修改handler⾃动转换
先写⼀个Handler继承ResultHandler
package;
import org.apache.ibatis.session.ResultContext;
import org.apache.ibatis.session.ResultHandler;
import java.util.HashMap;
import java.util.Map;
public class MapResultHandler implements ResultHandler {
@SuppressWarnings("rawtypes")
private final Map mappedResults = new HashMap();
@SuppressWarnings("unchecked")
@Override
public void handleResult(ResultContext context) {
@SuppressWarnings("rawtypes") Map map = (Map) ResultObject();
// xml配置中通过resultMap配置的property
mappedResults.("key"), ("value"));
}
@SuppressWarnings("rawtypes")
public Map getMappedResults() {
return mappedResults;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-////DTD Mapper 3.0//EN" "/dtd/mybatis-3-mapper.dtd">
<mapper namespace="DB.NationnalityCodeMapper">
<resultMap id="BaseResultMap" type="DB.NationnalityCodePO">
<id column="NATIONALITY_CODE" jdbcType="VARCHAR" property="nationalityCode"/>
<result column="NATIONALITY_DESC" jdbcType="VARCHAR" property="nationalityDesc"/>
</resultMap>
<resultMap id="mapResult" type="HashMap">
<!-- 这⾥的property需要与handler中的名称对应 -->
<result property="key" column="NATIONALITY_CODE" javaType="java.lang.String"/>
<result property="value" column="NATIONALITY_DESC" javaType="java.lang.String"/>
</resultMap>
<select id="selectAllMap" resultMap="mapResult">
select NATIONALITY_CODE, NATIONALITY_DESC
from T_NATIONALITY_CODE
</select>
</mapper>
需要查询时,不使⽤原来的mapper接⼝,新建⼀个查询类,使⽤@Repository注⼊并且继承SqlSessionDaoSupport,从⽽可以获取SqlSession对象import MapResultHandler;
import org.apache.ibatis.session.SqlSessionFactory;
batis.spring.support.SqlSessionDaoSupport;
import org.springframework.stereotype.Repository;
import javax.annotation.Resource;
import java.util.Map;
@Repository
public class MapSessionMapper extends SqlSessionDaoSupport {
@Resource
public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
super.setSqlSessionFactory(sqlSessionFactory);
}
public Map<String, String> selectCountryMap() {
MapResultHandler handler = new MapResultHandler();
Map<String, String> map = MappedResults();
return map;
}
}
NationnalityCodeMapper
@Mapper
public interface NationnalityCodeMapper {
//这⾥不需要写接⼝,因为改造后的⽅法是通过MapSessionMapper来调⽤的
}
调⽤⽅式如上,通过获取SqlSession来调⽤sql并使⽤我们⾃⼰定义的handler解析结果,selectAllMap是我这⾥的业务⽅法名称,sql实现依旧在XML中编写
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论