Ibatis关联查询

两个表 Dept(部门)、 Emp(员工) 

部门中的列名 
id 部门id 
name 部门名称 

员工表中的列 
id 员工ID 
name 员工名称 
deptId 部门ID 

员工和部门为多对一得关系所以员工类中肯定要关联一个部门 
public class Emp { 
private String id ; 
private String name; 
private Dept dept; 
}  
public class Dept { 
private String id ; 
private String name; 
}  
getter setter方法省略 


1、插入员工信息操作 
因为员工表中有一列是部门ID所以做插入操作时要将一个部门对象set到员工对象中可以有下列两种操作 
配置文件 Emp.xml 
<insert id="insertEmp" parameterClass="Emp"> 
insert into emp (id, name, age, sex, birthday, deptId) values (#id#, #name#, #dept.id#) 
</insert> 
value 中的dept.id 为ibatis的进一步导航,因为emp对象中有一个部门对象,我们可以通过部门对象拿到部门id放到sqlz中。 

2、查询员工时我们也想查到他的部门信息 
配置文件 Emp.xml 
方法1:采用一条SQL语句搞定 
<resultMap class="Emp" id="resultEmp"> 
<result property="id" column="id"/> 
<result property="name" column="name"/> 
<result property="dept.name" column="dname"/> 
</resultMap> 

<select id="selectById" parameterClass="String" resultMap="resultEmp"> 
select e.id, e.name name d.name dname from emp e, dept d where e.deptid = d.id and e.id=#id# 
</select> 
方法2:采用 N + 1条 SQL搞定 
<resultMap class="Emp" id="resultEmp1"> 
<result property="id" column="id"/> 
<result property="name" column="name"/> 
<result property="dept" column="deptId" select="selectDetpByEmp"/> 
</resultMap> 

<select id="selectDetpByEmp" resultClass="Dept" parameterClass="String"> 
select * from dept where id=#deptId# 
</select> 

3、删除 假如我要删除部门的同时将该部门对应的员工全部删除 
一种方式我可以在业务方法中先用一条SQL将部门中所有的员工删除,然后再用一条SQL将部门删除 

不知都ibatis中是否提供了级联删除的功能项hibernate那样,大家共同探讨一下 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值