• 自定义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);
  • 相关阅读:
    初学设计模式【5】工厂方法模式——FactoryMethod
    Activity生命周期
    ACTIVITY状态保存
    初学设计模式【6】抽象工厂模式——AbstractFactory
    android Toast总结
    Android对话框总结
    【实用】无线调试android应用——ADB OVER NETWORK
    二分法求根与二分次数
    struts2__action执行顺序
    JDBC与Hibernate连接池
  • 原文地址:https://www.cnblogs.com/xiaoxiaoccaiya/p/11082964.html
Copyright © 2020-2023  润新知