使用resultMap定义查询结果集,实现关联查询
接下來介紹resultMap定義查詢結果集,實現(xiàn)關聯(lián)查詢
1 首先在接口中定義操作的方法
public interface EmployeeMapperPlus {
public Employee getEmpAndDept(Integer id);
}
2在xml里進行配置
<!--第一種進行配置
聯(lián)合查詢:級聯(lián)屬性封裝結果集
-->
<resultMap type="com.atguigu.mybatis.bean.Employee" id="MyDifEmp">
<id column="id" property="id"/>
<result column="last_name" property="lastName"/>
<result column="gender" property="gender"/>
<result column="did" property="dept.id"/>
<result column="departmentName" property="dept.departmentName"/>
</resultMap>
<!--
第二種配置使用association定義關聯(lián)的單個對象的封裝規(guī)則;
-->
<resultMap type="com.atguigu.mybatis.bean.Employee" id="MyDifEmp2">
<id column="id" property="id"/>
<result column="last_name" property="lastName"/>
<result column="gender" property="gender"/>
<!-- association可以指定聯(lián)合的javaBean對象
property="dept":指定哪個屬性是聯(lián)合的對象
javaType:指定這個屬性對象的類型[不能省略]
-->
<association property="dept" javaType="com.atguigu.mybatis.bean.Department">
<id column="did" property="id"/>
<result column="departmentName" property="departmentName"/>
</association>
</resultMap>
<!-- public Employee getEmpAndDept(Integer id);-->
<select id="getEmpAndDept" resultMap="MyDifEmp2">
SELECT e.id id,e.last_name last_name,e.email email ,e.gender gender,e.did eedid,
d.id did,d.dname departmentName FROM tbl_employee e,department d
WHERE e.did=d.id AND e.id=#{id}
</select>
3在junit里進行測試
@Test
public void test05() throws IOException{
SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
SqlSession openSession = sqlSessionFactory.openSession();
try{
EmployeeMapperPlus mapper = openSession.getMapper(EmployeeMapperPlus.class);
Employee empAndDept = mapper.getEmpAndDept(1);
System.out.println(empAndDept);
System.out.println(empAndDept.getDept());
}finally{
openSession.close();
}
}
轉載于:https://www.cnblogs.com/zhangzhiqin/p/8546241.html
總結
以上是生活随笔為你收集整理的使用resultMap定义查询结果集,实现关联查询的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 2.3 字典
- 下一篇: 树莓派进阶之路 (037) - 设置树莓