mybatis映射文件-(3)-resultType与简单查询

在sql映射文件中,简单的查询结果用resultType,复杂的查询结果(关联查询)用resultMap。

一、返回list集合

单元测试:
EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
List<Employee> like = mapper.getEmpsByLastNameLike("%e%");
for (Employee employee : like) {
	System.out.println(employee);
}

接口:
public List<Employee> getEmpsByLastNameLike(String lastName);

sql映射文件:
<!-- public List<Employee> getEmpsByLastNameLike(String lastName); -->
<!--resultType:如果返回的是一个集合,要写集合中元素的类型  -->
<select id="getEmpsByLastNameLike" resultType="com.mybatis.bean.Employee">
	select * from tbl_employee where last_name like #{lastName}
</select>

二、返回map

1、一个Employee 对应的 map
举例:{id=1, [email protected], last_name=mike, gender=0}

单元测试:
Map<String, Object> map = mapper.getEmpByIdReturnMap(1);
System.out.println(map);

接口:
//返回一条记录的map;key就是列名,值就是对应的值
public Map<String, Object> getEmpByIdReturnMap(Integer id);
	
sql映射文件:
<!--public Map<String, Object> getEmpByIdReturnMap(Integer id);  -->
 <select id="getEmpByIdReturnMap" resultType="map">
 	select * from tbl_employee where id=#{id}
 </select>

2、多个Employee对应的map

单元测试:
Map<String, Employee> map = mapper.getEmpByLastNameLikeReturnMap("%r%");
System.out.println(map);

接口:
//多条记录封装一个map:Map<Integer,Employee>:键是这条记录的主键,值是记录封装后的javaBean
//@MapKey:告诉mybatis封装这个map的时候使用哪个属性作为map的key
@MapKey("email")
public Map<String, Employee> getEmpByLastNameLikeReturnMap(String lastName);

sql映射文件:
<!--public Map<Integer, Employee> getEmpByLastNameLikeReturnMap(String lastName);  -->
 <select id="getEmpByLastNameLikeReturnMap" resultType="com.mybatis.bean.Employee">
 	select * from tbl_employee where last_name like #{lastName}
 </select>

测试结果:

{[email protected]=Employee [id=4, lastName=null, [email protected], gender=1]}

 

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments