上篇中已经介绍了如何创建外键,以下是实现的demo效果
从中我们可以查询出t_student中的学生信息以及其对应班级信息,并且可以根据id进行增删查改。
1、实体类代码
package com.ydf.demo.pojo;
import lombok.Data;
@Data
public class Student {
private int stu_id; //学生主键
private String stu_name; //学生姓名
private int stu_classid; //班级表外键
private Grade grades; //班级对象
//注:如果没有配置lombok依赖 删除@Data注解 添加get set toString方法
}
package com.ydf.demo.pojo;
import lombok.Data;
@Data
public class Grade {
private int class_id; //班级主键
private String class_name; //班级名称
}
2、控制层代码
/***
* 查询所有学生相关信息
* @return
*/
@RequestMapping(value = "/")
public String testModel(Model model){
List<Student> studentList = studentService.selectStudent();
System.out.println("学生所有信息===="+studentList);
model.addAttribute("studentList",studentList);
return "/index";
}
(service)服务层、(dao)数据访问层省略…
3、StudentMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.ydf.demo.dao.StudentDao">
<resultMap type="com.ydf.demo.pojo.Student" id="studentMap">
<id column="stu_id" property="stu_id"/>
<result column="stu_name" property="stu_name"/>
<association property="grades" javaType="com.ydf.demo.pojo.Grade">
<id column="did" property="class_id"/>
<id column="dname" property="class_name"/>
</association>
</resultMap>
<select id="selectStudent" resultMap="studentMap">
select u.stu_id,u.stu_name,d.class_id did,d.class_name dname
from t_student u,t_class d where u.stu_classid=d.class_id
</select>
</mapper>
sql语句
select u.stu_id,u.stu_name,d.class_id did,d.class_name dname from t_student u,t_class d where u.stu_classid=d.class_id
4、index.html
<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>测试</title>
<link type="text/css" rel="stylesheet" th:href="@{/bootstrap-4.3.1-dist/css/bootstrap.css}" >
</head>
<body>
<table class="table table-hover">
<thead class="thead-dark">
<tr>
<th scope="col">#</th>
<th scope="col">姓名</th>
<th scope="col">所在班级</th>
<th scope="col">编辑</th>
</tr>
</thead>
<tbody>
<tr th:each="stu:${studentList}">
<td th:text="${stu.stu_id}"></td>
<td th:text="${stu.stu_name}"></td>
<td th:text="${stu.grades.class_name}"></td>
<td><a th:href="@{'/stuInfo/'+${stu.stu_id}}">查看</a></td>
</tr>
</tbody>
</table>
<script th:src="@{/jquery-2.2.4/jquery.min.js}"></script>
<script th:src="@{/bootstrap-4.3.1-dist/js/bootstrap.js}"></script>
</body>
</html>
如果搭建的框架为SSM 则table表改为c标签的遍历循环,很简单。
<c:forEach items="${studentList}" var="stu">
...省
</c:forEach>