本文内容来自上硅谷
1返回的结果集为一条时返回map对象
1.1xml配置如下
resultType为map
<select id="getEmpByIdReturnMap" resultType="map">
select * from tbl_employee where id=#{id}
</select>
1.2dao
//返回一条记录的map;key就是列名,值就是对应的值
public Map<String, Object> getEmpByIdReturnMap(Integer id);
1.3Junit
@Test
public void test04() throws IOException{
SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
SqlSession openSession = sqlSessionFactory.openSession();
try{
EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
Map<String, Object> map = mapper.getEmpByIdReturnMap(1);
System.out.println(map);
}finally{
openSession.close();
}
}
1.4效果
2如果返回多条记录要封装在map中
2.1xml
返回类为employee
<!--public Map<Integer, Employee> getEmpByLastNameLikeReturnMap(String lastName); -->
<select id="getEmpByLastNameLikeReturnMap" resultType="com.atguigu.mybatis.bean.Employee">
select * from tbl_employee where last_name like #{lastName}
</select>
2.2dao
@MapKey:告诉mybatis封装这个map的时候使用哪个属性作为map的key
//多条记录封装一个map:Map<Integer,Employee>:键是这条记录的主键,值是记录封装后的javaBean
//@MapKey:告诉mybatis封装这个map的时候使用哪个属性作为map的key
@MapKey("lastName")
public Map<String, Employee> getEmpByLastNameLikeReturnMap(String lastName);
2.3Junit
@Test
public void test04() throws IOException{
SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
SqlSession openSession = sqlSessionFactory.openSession();
try{
EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
Map<String, Employee> map = mapper.getEmpByLastNameLikeReturnMap("%r%");
System.out.println(map);
}finally{
openSession.close();
}
}
2.4效果
版权声明:本文不是「本站」原创文章,版权归原作者所有 | 原文地址: