---
title: "ibatis  插入 查询 删除 多表关联"
author: "andongoop"
date: "2009-09-18T09:03:07Z"
tags: []
slug: "ibatis"
draft: false
lastmod: "2009-09-18T09:11:12Z"
id: 470923
url: "https://andongoop.iteye.com/blog/470923"
---

两个表 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那样，大家共同探讨一下
		
上面的内容如有不妥还请指点。