数据表与一对多中一致
修改实体类
多对一:在多方创建一个存储一方数据的对象
Student类
public class Student {
private int stuid;
private String stuname;
//外键列一般不生成属性
private int teacherid;
private Teacher teacher;
public int getStuid() {
return stuid;
}
public void setStuid(int stuid) {
this.stuid = stuid;
}
public String getStuname() {
return stuname;
}
public void setStuname(String stuname) {
this.stuname = stuname;
}
public Teacher getTeacher() {
return teacher;
}
public void setTeacher(Teacher teacher) {
this.teacher = teacher;
}
}
Teacher类
public class Teacher {
private int tid;
private String tname;
public int getTid() {
return tid;
}
public void setTid(int tid) {
this.tid = tid;
}
public String getTname() {
return tname;
}
public void setTname(String tname) {
this.tname = tname;
}
}
TeacherDao接口
public interface TeacherDao{
//查询所有的学生(包含老师的信息)
public List<Student> getAll();
}
实现类
public class TeacherDaoImpl implements TeacherDao {
public List<Student> getAll() {
//操作数据库
Connection connection =null;
PreparedStatement pps =null;
ResultSet resultSet =null;
try {
//1.加载驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//2.获得链接
String userName="root";
String passWord="123456";
String url="jdbc:mysql://localhost:3306/yhp3?serverTimezone=UTC";
connection = DriverManager.getConnection(url, userName, passWord);
//3.定义sql,创建预状态通道(进行sql语句的发送)
String sql="select * from student s,teacher t where s.teacherid=t.tid";
pps = connection.prepareStatement(sql);
//执行sql resultSet = pps.executeQuery();
List<Student> students=new ArrayList<>();
while (resultSet.next()){
//1.取出各自的信息 Student student = new Student(); student.setStuId(resultSet.getInt("stuid")); student.setStuName(resultSet.getString("stuname"));
Teacher teacher = new Teacher();
teacher.setTid(resultSet.getInt("tid"));
teacher.setTname(resultSet.getString("tname"));
//2.建立学生和老师之间的关系
student.setTeacher(teacher);
students.add(student);
}
return students;
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
try {
//5.关闭资源
if (resultSet != null) {
resultSet.close();
}
if (pps != null) {
pps.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
return null;
}
}
测试类Demo
public class Demo{
public static void main(String[] args) {
TeacherDao dao= new TeacherDaoImpl();
List<Student> students = dao.getAll();
for (Student student : students) { System.out.println(student.getStuName()+","+student.getTeacher().getTname());
}
}
}
结果:
aaa,王五
bb,张三老师
cc,王五
dd,张三老师
ee,张三老师
ff,李四老师