查询返回List
resultType:如果返回的是一个集合,resultType要写集合中元素的类型
接口:
public List<Employee> selectEmpByName(String lastName);
配置文件
<select id="selectEmpByName"
resultType="com.fish.mybatis.Employee">
select * from tbl_employee where last_name like "%" #{lastName} "%"
</select>
测试代码
@org.junit.Test
public void test02() throws IOException {
//读取配置文件
String resource = "config/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
//获取SqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession openSession = sqlSessionFactory.openSession();
//调用getMapper方法获取该接口的实现类
EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
List<Employee> selectEmpByName = mapper.selectEmpByName("2");
System.out.println(selectEmpByName);
//关闭Session
openSession.close();
}
运行结果
[Employee [id=5, lastName=2, email=lisi@163.com, gender=1]]
记录封装map
resultType直接写map
查询结果为一条
如果resultType写的是map,则map的key对应的是列名,value对应的是列名对应的值
接口
public Map<String,Object> selectEmpByNameMap(Integer id);
配置文件
<select id="selectEmpByNameMap"
resultType="map">
select * from tbl_employee where id = #{id}
</select>
测试代码
@org.junit.Test
public void test03() throws IOException {
//读取配置文件
String resource = "config/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
//获取SqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession openSession = sqlSessionFactory.openSession();
//调用getMapper方法获取该接口的实现类
EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
Map<String, Object> selectEmpByNameMap = mapper.selectEmpByNameMap(1);
System.out.println(selectEmpByNameMap);
//关闭Session
openSession.close();
}
}
运行结果
{gender=1, last_name=1, id=1, email=ZFH_FISH@163.COM}
查询结果为多条
如果查询结果为多条,且我们想把每一条记录对应的key设置为这条记录的主键,那么resultType写map元素的类型,这里怎么指定记录的主键为map的key呢,只需在接口上使用@MapKey("id")注解即可
接口
@MapKey("id")
public Map<String,Employee> selectEmpByNameMap2(String lastName);
配置文件
resultType="com.fish.mybatis.Employee">
select * from tbl_employee where last_name like "%" #{lastName} "%"
测试代码
@org.junit.Test
public void test04() throws IOException {
//读取配置文件
String resource = "config/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
//获取SqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession openSession = sqlSessionFactory.openSession();
//调用getMapper方法获取该接口的实现类
EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
Map<String, Employee> selectEmpByNameMap2 = mapper.selectEmpByNameMap2("2");
System.out.println(selectEmpByNameMap2);
//关闭Session
openSession.close();
}
运行结果
{1=Employee [id=1, lastName=222, email=ZFH_FISH@163.COM, gender=1], 5=Employee [id=5, lastName=22, email=lisi@163.com, gender=1]}