• 自定义Mybatis返回类型及注意事项


    一、自定义返回拦截器
    package com.yaoex.crm.service.util;

    import org.apache.ibatis.session.ResultContext;
    import org.apache.ibatis.session.ResultHandler;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.mybatis.spring.SqlSessionTemplate;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Component;

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

    /**
    * @Title: MapResultHandler
    * @Package: com.yaoex.crm.service.util
    * @description:
    **/

    @Component
    public class MapResultHandler implements ResultHandler {
    private static final Logger log = LoggerFactory.getLogger(MapResultHandler.class);

    private static SqlSessionTemplate sqlSessionTemplate;

    @Autowired
    public void setSqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
    MapResultHandler.sqlSessionTemplate = new SqlSessionTemplate(sqlSessionFactory);
    }

    @SuppressWarnings("rawtypes")
    private final Map mappedResults = new HashMap();

    @SuppressWarnings("unchecked")
    @Override
    public void handleResult(ResultContext context) {
    @SuppressWarnings("rawtypes")
    Map map = (Map) context.getResultObject();
    if(map.get("key") != null && map.get("value") != null ){
    // xml配置里面的property的值,对应的列
    mappedResults.put(map.get("key"), map.get("value"));
    }
    }

    @SuppressWarnings("rawtypes")
    public Map getMappedResults() {
    return mappedResults;
    }

    public static Map getMapResults(String statementId,Map<String,Object> param){
    MapResultHandler handler = new MapResultHandler();
    sqlSessionTemplate.select(statementId,param,handler);
    return handler.getMappedResults();
    }
    }

    二、mybatis配置
    <resultMap id="levelCountMap" type="java.util.Map" >
    <result column="cust_level" property="key" jdbcType="INTEGER" />
    <result column="count" property="value" jdbcType="INTEGER" />
    </resultMap>

    <select id="selectCountByLevel" resultMap="levelCountMap">
    SELECT l.cust_level,COUNT(l.cust_level) as count from t_crm_customer_level l
    GROUP BY l.cust_level
    </select>

    三、调用方式
    Map<Integer,Long> results = MapResultHandler.getMapResults("com.yaoex.crm.dao.customerdata.CrmCustomerLevelDao.selectCountByLevel", null);
  • 相关阅读:
    计算机三级数据库-指导
    spring导入约束
    hibernater获取session时org.hibernate.service.spi.ServiceException错误
    springxml配置注入报错
    右键复制类的完整路径
    关于实体里的toString方法
    idea创建web项目环境
    框架快速找类
    如何在scdn博客里搜索自己博客文章
    永久消除自动产生的QQPCMgr
  • 原文地址:https://www.cnblogs.com/xiaoxiaoccaiya/p/11082964.html
Copyright © 2020-2023  润新知