在多值查询的时候,通常要把方法返回类型设置为List类型,Mybatis为我们提供了另一种解决方式,通过K-V的形式将查询结果保存在Map中,这种实现方式只需要在方法上标注为@Mapkey即可。
如下代码:查询一个学生表,包含id,name,age三个字段,使用@mapkey将id号作为K,查询结果作为V.使用@Mapkey时最好将K设置为唯一的,否则后续的结果将会覆盖已查询到的结果,如果设置的@Mapkey设置的value为空或者一个跟查询结果不匹配的字段,那么查到的记录K成了null,查询结果始终都是最后一条。
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Flush;
import org.apache.ibatis.annotations.MapKey;
import org.apache.ibatis.annotations.Select;
public interface SqlMapper {
public List<Map<String, Object>> list();
@Flush
public void flush();
@MapKey(value="id")
@Select("select id,name,age from student")
public Map<String,Map<String,String>> listByMapkey();
}
import java.util.List;
import java.util.Map;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;
import com.zzz.mybatis.mapper.SqlMapper;
import com.zzz.mybatis.mapper.StudentMapper;
public class StudentMapperTest {
private SqlSession session;
private StudentMapper mapper;
@Before
public void before() {
SqlSessionFactoryBuilder builder =new SqlSessionFactoryBuilder();
SqlSessionFactory sessionFactory=builder.build(Class.class.getResourceAsStream("/mybatis-config.xml"));
this.session=sessionFactory.openSession(false);
}
@Test
public void getStuByMapkey() {
mapper=session.getMapper(StudentMapper.class);
mapper.flush();
Map<String, Map<String, String>> rs=mapper.listByMapkey();
System.out.println(rs.toString());
}
}
{1={name=zhangsan, id=1, age=20}, 2={name=lisi, id=2, age=30}, 3={name=wangwu, id=3, age=40}}
@Override
public void handleResult(ResultContext<? extends V> context) {
final V value = context.getResultObject();
final MetaObject mo = MetaObject.forObject(value, objectFactory, objectWrapperFactory, reflectorFactory);
// TODO is that assignment always true?
final K key = (K) mo.getValue(mapKey);
mappedResults.put(key, value);
}
通过源码中的DefaultMapResultHandler
类得出结果,代码见最后, final K key = (K) mo.getValue(mapKey);这句代码就是将@Mapkey中指定的类型字段查询出对应的value值,再将value值作为最终结果的key。