mybaits八:select查询返回map集合

返回一条纪录的map

package com.atChina.dao;

import java.util.List;
import java.util.Map;

import org.apache.ibatis.annotations.MapKey;
import org.apache.ibatis.annotations.Param;

import com.atChina.bean.Employee;

public interface EmployeeMapper {
	
	// 返回一条纪录的map, key是列名, value是对应的值
	public Map<String,Object> getEmpByDepno(Integer depno);
}

 sql配置文件

<select
		id="getEmpByDepno"  
		resultType="map" >
		select * from DEPTTEST where deptno = #{deptno}
	</select>

测试方法:

@Test
	public void test22() throws IOException {
		String resource = "mybatis-config.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		
		SqlSession openSession = sqlSessionFactory.openSession();
		try{
			// 命名空间.id,这样别的配置文件里有同名的id,程序也不报错
			EmployeeMapper em = openSession.getMapper(EmployeeMapper.class);
			System.out.println(em.getClass()); // 动态代理类
			
			Map<String, Object> map = em.getEmpByDepno(10);
			
			System.out.println(map+" "+map.size());
		}finally{
			// 关闭
			openSession.close();
		}
	}

 返回多条纪录的map

package com.atChina.dao;

import java.util.List;
import java.util.Map;

import org.apache.ibatis.annotations.MapKey;
import org.apache.ibatis.annotations.Param;

import com.atChina.bean.Employee;

public interface EmployeeMapper {
	
	// 返回多条纪录的map, key是主键, value是封装后的javaBean
	@MapKey("deptno") // @Mapkey("告诉mybatis使用javaBean的某个属性的值作为map的key")
	public Map<String,Employee> getEmpByDepnos(Integer depno);
}
<select
		id="getEmpByDepnos"  
		resultType="com.atChina.bean.Employee" >
		select * from DEPTTEST where deptno >= #{deptno}
	</select>
@Test
	public void test23() throws IOException {
		String resource = "mybatis-config.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		
		SqlSession openSession = sqlSessionFactory.openSession();
		try{
			// 命名空间.id,这样别的配置文件里有同名的id,程序也不报错
			EmployeeMapper em = openSession.getMapper(EmployeeMapper.class);
			System.out.println(em.getClass()); // 动态代理类
			
			Map<String, Employee> map = em.getEmpByDepnos(10);
			
			System.out.println(map+" "+map.size());
		}finally{
			// 关闭
			openSession.close();
		}
	}

猜你喜欢

转载自blog.csdn.net/m0_37564426/article/details/88917530