String sqlb="insert into employee (id,name,salary,department_id) values(?,?,?,?)";

package com.tfy.itheima.dao.impl;


import java.util.List;


import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;


import com.tfy.itheima.domain.Department;
import com.tfy.itheima.domain.Employee;
import com.tfy.itheima.jdbc.util.DbcpUtil;


public class DepartmentDaoImpl {
private QueryRunner qr=new QueryRunner(DbcpUtil.getDataSource());
public void addDepartment(Department dept){
try{
//保存部门的基本信息
String sqla="insert into department (id,name) values(?,?)";
Object params1[]={dept.getId(),dept.getName()};
qr.update(sqla, params1);
//看dept有没有关联的员工信息
List emps=dept.getEmps();
//如果有,还要将员工的信息保存到Employeee表中
if(emps!=null && emps.size()>0){
String sqlb="insert into employee (id,name,salary,department_id) values(?,?,?,?)";
Object [][] params2=new Object[emps.size()][];
for(int i=0;i Employee e=emps.get(i);
params2[i]=new Object[]{e.getId(),e.getName(),e.getSalary(),dept.getId()};

}
qr.batch(sqlb, params2);
}

}catch(Exception e){
e.printStackTrace();
throw new RuntimeException(e);
}
}
//对于多的一方,要不要查出来,看业务需求
public Department findDepartmentById(Integer deptId){
return findDepartmentById(deptId, true);
/*try{
String sql1="select * from department where id=?";
Department dept = qr.query(sql1, new BeanHandler(Department.class),deptId);

String sql2="select * from employee where department_id=?";
List emps = qr.query(sql2, new BeanListHandler(Employee.class), deptId);

if(emps!=null){
dept.setEmps(emps);
}
return dept;
}catch(Exception e){
e.printStackTrace();
throw new RuntimeException(e);
}*/
}
//对于多的一方,要不要查出来,看业务需求
public Department findDepartmentById(Integer deptId,boolean lazy){
try{
String sql1="select * from department where id=?";
Department dept = qr.query(sql1, new BeanHandler(Department.class),deptId);

if(lazy){
String sql2="select * from employee where department_id=?";
List emps = qr.query(sql2, new BeanListHandler(Employee.class), deptId);

if(emps!=null){
dept.setEmps(emps);
}
}
return dept;
}catch(Exception e){
e.printStackTrace();
throw new RuntimeException(e);
}
}
}

你可能感兴趣的:(String sqlb="insert into employee (id,name,salary,department_id) values(?,?,?,?)";)