String sql3="insert into teacher_student (teacher_id,student_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.Student;
import com.tfy.itheima.domain.Teacher;
import com.tfy.itheima.jdbc.util.DbcpUtil;


public class TeacherDaoImpl {
private QueryRunner qr=new QueryRunner(DbcpUtil.getDataSource());
public void addTeacher(Teacher t){
try{

//保存教师的基本信息
String sql1="insert into teacher (id,name,salary) values(?,?,?)";
Object []params1={t.getId(),t.getName(),t.getSalary()};
 
qr.update(sql1, params1);
//如果有学生的话,则保存学生的基本信息,并在第三方的表中建立关系
List<Student> students = t.getStudents();
if(students!=null && students.size()>0){
String sql2="insert into student (id,name,grade) values(?,?,?)";
String sql3="insert into teacher_student (teacher_id,student_id) values(?,?)";
Object [][]params2=new Object[students.size()][];
Object [][]params3=new Object[students.size()][];
for(int i=0;i<students.size();i++){
Student s = students.get(i);
params2[i]=new Object[]{s.getId(),s.getName(),s.getGrade()};
params3[i]=new Object[]{t.getId(),s.getId()};
}
qr.batch(sql2, params2);
qr.batch(sql3, params3);
}

}catch(Exception e){
e.printStackTrace();
throw new RuntimeException(e);
}


}
//把学生的基本信息查询出来
public Teacher findTeacherById(Integer teacherId){
try{
String sql1="select * from teacher where id=?";
Teacher t = qr.query(sql1, new BeanHandler<Teacher>(Teacher.class),teacherId);
//查询学生基本信息
if(t!=null){
// String sql2="select s.* from student s ,teacher_student ts where s.id=ts.student_id and ts.teacher_id=?";
// String sql2="select s.* from student s inner join teacher_student ts on s.id=ts.student_id where ts.teacher_id=?";
String sql2="select * from student where id in(select student_id from teacher_student where teacher_id=?)";
List<Student> students = qr.query(sql2, new BeanListHandler<Student>(Student.class), teacherId);
t.setStudents(students);


}
return t;

}catch(Exception e){
e.printStackTrace();
throw new RuntimeException(e);
}

}
}

你可能感兴趣的:(String sql3="insert into teacher_student (teacher_id,student_id) values(?,?)";)