mybatis查询结果返回map,选取表的两个字段分别作为key和value

Mapper.xml 书写

定义resultMap

    
        
        
    

查询语句

    

SelectMapKeyAndValue .java 书写

import org.apache.ibatis.session.ResultContext;
import org.apache.ibatis.session.ResultHandler;

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

// yanghaiyun 重写返回mybatis返回map

public class SelectMapKeyAndValue implements ResultHandler {
    @SuppressWarnings("rawtypes")
    private final Map mappedResults = new HashMap();
    @SuppressWarnings("unchecked")
    @Override
    public void handleResult(ResultContext context) {
        @SuppressWarnings("rawtypes")
        Map map = (Map) context.getResultObject();
        mappedResults.put(map.get("key"), map.get("value"));  // xml 配置里面的property的值,对应的列
    }
    @SuppressWarnings("rawtypes")
    public Map getMappedResults() {
        return mappedResults;
    }
}

SessionMapper.java 书写

import com.at21.nsbd.inspection.common.utils.SelectMapKeyAndValue;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;
@Service
public class SessionMapper extends SqlSessionDaoSupport {
    @Resource
    public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
        super.setSqlSessionFactory(sqlSessionFactory);
    }
    /**
     * @return
     */
    @SuppressWarnings("unchecked")
    public Map selectWorkMap(String id){
        SelectMapKeyAndValue handler = new SelectMapKeyAndValue();
        //namespace : XxxMapper.xml 中配置的地址(XxxMapper.xml的qualified name)
        //.selectXxxxNum : XxxMapper.xml 中配置的方法名称
        //this.getSqlSession().select(namespace+".selectXxxxNum", handler);
        String planScheduleId = id;
        this.getSqlSession().select(PlanWorkInfoDetailRepository.class.getName()+".selectPlanWorkInfoMap",planScheduleId, RowBounds.DEFAULT, handler);
        Map map = handler.getMappedResults();
        return map;
    }
}

运行

Map map = sessionMapper.selectWorkMap(PlanScheduleId);

 

你可能感兴趣的:(j2se)