SpringBoot学习笔记(八)MyBatis多表查询练习

MyBatis多表查询练习

6.1 创建项目

6.1.1 项目依赖

新建SpringBoot项目(版本2.4.2),添加Web下的“Spring Web”、Template Engines下的“Thymeleaf”、SQL下的“MyBatis Framework”和“MySQL Driver”。

6.1.2 创建数据库

本练习学习MyBatis的一对一、一对多、多对多表间关系的查询,各表的字段与关系如下图所示

学生与班长为一对一关系,因此,需要在任意一端加入另一端的主键,本例在班长端加入学生表的主键student_id;学生表与课程表之间是多对多的关系,因此,利用中间表描述两者间的关系,中间表为成绩表,其中包含学生表主键student_id、课程表主键course_id,以及学生取得的相关课程的成绩。

1.建立数据库和表

数据库名称:db_study。数据表名称如上图中所示。命令如下:

create database db_study;
use db_study;
create table t_student(
       id int(12) not null auto_increment,
       name varchar(12),
       number varchar(11),
       sex int(1) default 1 check(sex in (0,1)),
       age int default 1 check(age in(1,200)),
       address varchar(256),
       primary key(id)
);
create table t_classmonitor(
       id int(12) not null auto_increment,
       name varchar(50),
       student_id int not null default 0,
       primary key(id),
       constraint fk_studentid foreign key(student_id) references t_student(id)
);

create table t_course(
       id int(12) not null auto_increment,
       name varchar(60),
       primary key(id)
);
create table t_achievement(
       id int(12) not null auto_increment,
       student_id int not null default 0,
       course_id int not null default 0,
       achievement int default 0,
       primary key(id),
       constraint fk_studentid foreign key(student_id) references t_student(id),
       constraint fk_courseid foreign key(course_id) references t_course(id)
);

插入相关的测试数据。

6.2 项目配置

6.2.1 数据源配置

配置src/main/resources下的application.properties文件,配置内容如下:

#配置数据库驱动程序
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#配置数据库URL
spring.datasource.url=jdbc:mysql://localhost:3306/db_study?serverTimezone=UTC
#配置数据库服务器用户名
spring.datasource.username=root
#配置数据库服务器密码
spring.datasource.password=root

6.2.2 配置MyBatis

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!--导入外部配置文件-->
    <properties resource="application.properties"/>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${spring.datasource.driver-class-name}"/>
                <property name="url" value="${spring.datasource.url}"/>
                <property name="username" value="${spring.datasource.username}"/>
                <property name="password" value="${spring.datasource.password}"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <!--
        配置Mapper.xl文件的路径
        <mapper resource="com/sky/demo/dao/AccountMapper.xml" />
        -->
        <package name="com.bluesky.mybatisstudy.dao"/>
    </mappers>
</configuration>

6.3 创建实体类与Mapper

6.3.1创建实体类

学生实体类对应于数据表t_student,同时由于其与课程表(t_course)属于多对多关系,因为一个学生可以学习多门课程,一门课程又可以被多个学生学习。两者的关系是通过数据表(t_achievement)关联的。所以也需要创建对应的实体类。

学生与班长是一对一的关系,所以在班长端加入了学生端的主键,创建实体类时,注意体现。

具体代码如下:

1.Student类

package com.bluesky.mybatisstudy.entity;

import java.util.List;

public class Student {
    private int id;
    private String name;
    private String number;
    private int sex;
    private int age;
    private String address;
    //此处省略其setter和getter
}

2.Course类

package com.bluesky.mybatisstudy.entity;

import java.util.List;
public class Course {
    private int id;
    private String name;
    public int getId() {
        return id;
    }
//此处省略setter和getter
}

3.AchieveMent类

package com.bluesky.mybatisstudy.entity;

public class AchieveMent {
    private int id;
    private Student student;
    private Course course;
    private int achievement;
    //此处省略setter和getter
}

4.ClassMonitor类

package com.bluesky.mybatisstudy.entity;

import org.apache.catalina.User;

public class ClassMonitor {
    private int id;
    private String name;
    private Student student;
//此处省略setter和getter
}

6.3.2 创建基于接口的Mapper

1.创建DBUtil

在com.bluesky.mybatisstudy下新建包util,在包中创建DButil类,代码如下:

package com.bluesky.mybatisstudy.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class DBUtil {
    private static SqlSessionFactory sqlSessionFactory;
    static {
        String resource="mybatis-config.xml";
        try {
            InputStream in= Resources.getResourceAsStream(resource);
            sqlSessionFactory=new SqlSessionFactoryBuilder().build(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static SqlSession getSession(){
        return sqlSessionFactory.openSession();
    }
}

2.创建基于接口的Mapper

在com.bluesky.mybatisstudy下创建dao包,在其中创建Mapper接口,

1)IStudentMapper接口

package com.bluesky.mybatisstudy.dao;

import com.bluesky.mybatisstudy.entity.Student;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;

import java.util.List;
public interface IStudentMapper {
    @Select(value = "select * from t_student where id=#{id}")
    @Results({
            @Result(property = "id",column = "id"),
            @Result(property = "name",column = "name"),
            @Result(property = "number",column = "number"),
            @Result(property = "sex",column = "sex"),
            @Result(property = "age",column="age"),
            @Result(property = "address",column = "address")
    })
    public Student getStudentByID(int id);
}

2)IClassMonitorMapper接口

package com.bluesky.mybatisstudy.dao;

import com.bluesky.mybatisstudy.entity.ClassMonitor;
import org.apache.ibatis.annotations.One;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;

public interface IClassMonitorMapper {
    @Select(value = "select * from t_classmonitor where id=#{id} ")
    @Results({
            @Result(property = "id",column = "id"),
            @Result(property = "name",column = "name"),
            @Result(property = "student",column="student_id",
                one = @One(select = "com.bluesky.mybatisstudy.dao.IStudentMapper.getStudentByID"))
    })
    public ClassMonitor getClassMonitorByID(int id);
}

6.4 创建业务类与控制器

6.4.1 创建业务类

1.StudentService类

package com.bluesky.mybatisstudy.service;

import com.bluesky.mybatisstudy.dao.IStudentMapper;
import com.bluesky.mybatisstudy.entity.Student;
import com.bluesky.mybatisstudy.util.DBUtil;
import org.springframework.stereotype.Service;

@Service
public class StudentService {
    //取得SqlSession对象
    private IStudentMapper studentMapper= DBUtil.getSession().getMapper(IStudentMapper.class);

    /**
     * 根据编号取得学生信息
     * @param id 学生主键值
     * @return Student对象
     */
    public Student getStudentByID(int id){
        return studentMapper.getStudentByID(id);
    }
}

2.ClassMonitorService类

package com.bluesky.mybatisstudy.service;

import com.bluesky.mybatisstudy.dao.IClassMonitorMapper;
import com.bluesky.mybatisstudy.entity.ClassMonitor;
import com.bluesky.mybatisstudy.util.DBUtil;
import org.springframework.stereotype.Service;

@Service
public class ClassMonitorService {
    //创建数据访问对象
    private IClassMonitorMapper classMonitorMapper= DBUtil.getSession().getMapper(IClassMonitorMapper.class);

    /**
     * 根据编号取得班长信息
     * @param id 班长表的id
     * @return ClassMonitor对象
     */
    public ClassMonitor getClassMonitorByID(int id){
        return classMonitorMapper.getClassMonitorByID(id);
    }
}

6.4.2 创建控制器

1.StudentController控制器

package com.bluesky.mybatisstudy.controller;

import com.bluesky.mybatisstudy.entity.Student;
import com.bluesky.mybatisstudy.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.jws.Oneway;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/student")
public class StudentController {
    @Autowired
    private StudentService studentService;

    @GetMapping(value = "/getStu/{id}")
    public ResponseEntity<Map<String,Object>> getStudentByID(@PathVariable int id){
        Map<String,Object> map=new HashMap<>();
        Student stu=studentService.getStudentByID(id);
        map.put("data",stu);
        return new ResponseEntity<>(map, HttpStatus.OK);
    }
}

2.ClassMonitorConntroller控制器

package com.bluesky.mybatisstudy.controller;

import com.bluesky.mybatisstudy.entity.ClassMonitor;
import com.bluesky.mybatisstudy.service.ClassMonitorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/classmonitor")
public class ClassMonitorController {
    @Autowired
    private ClassMonitorService classMonitorService;

    @GetMapping("/getcm/{id}")
    public ResponseEntity<Map<String,Object>> getClassMonitorByID(@PathVariable int id){
        Map<String,Object> map=new HashMap<>();
        ClassMonitor cm=classMonitorService.getClassMonitorByID(id);
        map.put("data",cm);
        return new ResponseEntity<>(map, HttpStatus.OK);
    }
}

3.测试一对一访问

启动项目,测试对学生表的访问,结果如下:

测试对班长表的访问,访问班长表时,应该得到担任班长的学生的信息,结果如下:

6.4.3 实现课程、成绩查询

在com.bluesky.mybatisstudy下创建Mapper接口,

1.创建ICourseMapper

package com.bluesky.mybatisstudy.dao;

import com.bluesky.mybatisstudy.entity.Course;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;

public interface ICourse {
    /**
     * 根据课程主键查询课程信息
     * @param id 课程主键
     * @return Course类对象
     */
    @Select(value = "select * from t_course where id=#{id}")
    @Results({
            @Result(property = "id",column = "id"),
            @Result(property = "name",column = "name")
    })
    public Course getCourseByID(int id);
}

2.创建IAchieveMent

package com.bluesky.mybatisstudy.dao;

import com.bluesky.mybatisstudy.entity.AchieveMent;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface IArchieveMentMapper {
    @Select(value = "select * from t_achievement where student_id=#{stu_id} ")
    @Results({
            @Result(property = "id",column = "id"),
            @Result(property = "student",column = "student_id"),
            @Result(property = "course",column = "course_id")
    })
    public List<AchieveMent> getAchieveMentByStudentID(int stu_id);
}

3.创建IAchieveMentController控制器

package com.bluesky.mybatisstudy.controller;

import com.bluesky.mybatisstudy.entity.AchieveMent;
import com.bluesky.mybatisstudy.service.AchieveMentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/archievement")
public class ArchievementController {
    @Autowired
    private AchieveMentService achieveMentService;
    @GetMapping(value = "/getByStuID/{id}")
    public ResponseEntity<Map<String,Object>> getArchievementByStudentID(@PathVariable int id){
        Map<String,Object> map=new HashMap<>();
        List<AchieveMent> achieveMents= achieveMentService.getArchievementByStudentID(id);
        map.put("data",achieveMents);
        return new ResponseEntity<>(map, HttpStatus.OK);
    }
}

4.测试

测试结果如下:

 

6.5 前端页面

为了进一步测试对数据表的访问操作,在前端页面进行数据的展示。需要使用BootStrap、Vue、vue-resource、axios框架。

6.5.1 创建首页

为了不使用跨域请求,本练习程序使用Thymeleaf模板引擎,所以,首先在controller包中创建控制器TestController,代码如下:

package com.bluesky.mybatisstudy.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/test")
public class TestController {
    @GetMapping("/index")
    public String index(){
        return "/test/index";
    }
}

在resources/templates下新建目录test,在test下新建文件index.html文件,代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>MyBatis学习程序</title>
</head>
<body>
<div>
    <h1>MyBatis学习</h1>
</div>
</body>
</html>

6.5.2 引入前端框架与分页

1.引入前端框架

前端页面引入BootStrap、Vue、vue-resource、axios框架,首先在resources/static目录下新建css、js目录,并将bootstrap.css复制到css目录下,将jquery.js、vue.js、vue-resource.min.js、axios.js文件复制到js目录中。

在页面中引用前端框架,代码如下:

<link rel="stylesheet" href="/css/bootstrap.css">
<script type="text/javascript" src="/js/vue.js"></script>
<script type="text/javascript" src="/js/vue-resource.min.js"></script>
<script type="text/javascript" src="/js/axios.js"></script>

2.分页的实现

分页比较麻烦,需要先通过查询取得所有的记录数,然后将总页数等信息发给前端,然后再写一个真正分页查询的语句。

1)首先在util中创建PageUtil类,在该类中封装分页的相关信息(记录数、页数、当前页、每页记录数、分页记录集)。代码如下:

package com.bluesky.mybatisstudy.util;

import java.util.List;

public class PageUtil<T> {
    private int currentPage;//分页起始页
    private int pageSize;//每页记录数
    private List<T> rows;//返回的记录集合
    private int total;//总记录数
    private int pages;//总页数

    public void setPages(){
        this.pages=(this.total+this.pageSize-1)/this.pageSize;
    }
    public int getPages(){
        return this.pages;
    }

    public int getCurrentPage() {
        return currentPage;
    }

    public void setCurrentPage(int currentPage) {
        this.currentPage = currentPage;
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    public List<T> getRows() {
        return rows;
    }

    public void setRows(List<T> rows) {
        this.rows = rows;
    }

    public int getTotal() {
        return total;
    }

    public void setTotal(int total) {
        this.total = total;
        this.setPages();
    }
}

2)然后在IStudentMapper接口中,配置两个查询,代码如下:

/**
* 取得表中记录数
* @return 表中记录数
*/
@Select(value = "select count(1) from t_student")
public int studentCount();
//分页查询
 @Select(value = "select * from t_student limit #{startPage},#{pageSize}")
@ResultMap("studentMap")
public List<Student> findByPager(@Param("startPage") int startPage,
    @Param("pageSize") int pageSize);

3)在StudentService中,添加分页查询方法

 /**
     * 分页查询方法
     * @param startPage 起始页
     * @param pageSize 页数
     * @return 分页后的数据
     */
    public PageUtil<Student> findByPager(int startPage,int pageSize){
        PageUtil<Student> pageUtil=new PageUtil<>();
        List<Student> list=studentMapper.findByPager(startPage*pageSize,pageSize);
        pageUtil.setPageSize(pageSize);
        pageUtil.setRows(list);
        pageUtil.setTotal(studentMapper.studentCount());
        return pageUtil;
    }

4)在StudentController控制器,添加如下方法

@GetMapping("/getStus/{startPage}/{pageSize}")
    public ResponseEntity<Map<String,Object>> getStudentsByPage(@PathVariable int startPage,@PathVariable int pageSize){
        Map<String,Object> map=new HashMap<>();
        PageUtil<Student> pages=studentService.findByPager(startPage,pageSize);
        map.put("data",pages);
        return new ResponseEntity<>(map,HttpStatus.OK);
    }

 

6.5.3 分页显示学生信息

本页面实现学生信息的分页显示。

首先在StudentController控制器中,增加如下代码,通过Thymeleaf模板引擎请求学生信息管理首页面。

@GetMapping("/index")
public String index(){
    return "/student/index";
}

然后在templates下新建目录student,在里面新建index.html文件,页面内容如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>学生信息管理</title>

    <link rel="stylesheet" href="/bootstrap.css">
    <script src="/vue.js" type="text/javascript"></script>
    <script src="/vue-resource.min.js" type="text/javascript"></script>
    <script src="/axios.js" type="text/javascript"></script>
    <script src="/jquery.js" type="text/javascript"></script>
    <script src="/bootstrap.js" type="text/javascript"></script>
</head>
<body>
<div id="app" class="container">
    <div class="row">
        <div class="col-md-12">
            <table class="table">
                <tr>
                    <td>编号</td>
                    <td>姓名</td>
                    <td>学号</td>
                    <td>性别</td>
                    <td>年龄</td>
                    <td>地址</td>
                </tr>
                <tr v-for="item in stus">
                    <td>{{item.id}}</td>
                    <td>{{item.name}}</td>
                    <td>{{item.number}}</td>
                    <td>{{item.sex}}</td>
                    <td>{{item.age}}</td>
                    <td>{{item.address}}</td>
                </tr>
            </table>
        </div>
        <div class="col-md-12">
            <nav aria-label="Page navigation">
                <ul class="pagination">
                    <li v-if="currentPage>0">
                        <a href="#" aria-label="Previous">
                            <span aria-hidden="true">&laquo;</span>
                        </a>
                    </li>
                    <li v-for="item in pageCount">
                        <a v-on:click="getStusData(item-1)">{{item}}</a>
                    </li>
                    <li v-if="currentPage*2<pageCount">
                        <a href="#" aria-label="Next">
                            <span aria-hidden="true">&raquo;</span>
                        </a>
                    </li>
                </ul>
            </nav>
        </div>
    </div>
</div>
<script>
    var app=new Vue({
        el:'#app',
        data:{
            currentPage:0,
            pageSize:2,
            pageCount:0,
            stus:[]
        },
        mounted:function(){
            this.$http.get(
                '/student/getStus/'+this.currentPage+'/'+this.pageSize
            ).then(function(res){
                this.stus=res.data.data.rows;
                this.pageCount=res.data.data.pages;
            }),function(error){
                alert(error);
            }
        },methods:{
            getStusData:function(currentPage){
                this.currentPage=currentPage;
                console.log('/student/getStus/'+this.currentPage+'/'+this.pageSize)
                this.$http.get(
                    '/student/getStus/'+currentPage+'/'+this.pageSize
                ).then(function(res){
                    this.stus=res.data.data.rows;
                    this.pageCount=res.data.data.pages;
                }),function(error){
                    alert(error);
                }
            }
        }
    })
</script>
</body>
</html>

结果如下

6.5.4 查询成绩

成绩的查询,有多种查询方式,查询某一学生所有课程的成绩、查询某一课程所有学生的成绩。

1.首页控制器

在ArchievementController类中,添加如下方法,

@GetMapping("/index")
    public String index(){
        return "/score/index";
    }

该方法用于返回前端页面,

2.创建index.html

在templates下,新建index.html文件,代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>成绩查询</title>

    <link rel="stylesheet" href="/bootstrap.css">
    <script src="/vue.js" type="text/javascript"></script>
    <script src="/vue-resource.min.js" type="text/javascript"></script>
    <script src="/axios.js" type="text/javascript"></script>
    <script src="/jquery.js" type="text/javascript"></script>
    <script src="/bootstrap.js" type="text/javascript"></script>
</head>
<body>

</body>
</html>

3.创建查询

第一种查询是根据学生的学号查询所有课程的信息,在IArchieveMentMapper中添加如下方法:

/**
     * 根据学号查询该学生所有课程的成绩
     * @param stuNumber 学生学号
     * @return StudentCourseScore对象集合
     */
    @Select(value = "select s.number as snumber,s.name as sname,c.name as cname,a.achievement " +
            "from t_student s,t_course c,t_achievement a " +
            "WHERE a.student_id=s.id and a.course_id=c.id and s.number=#{stuNumber} ")
    @Results({
            @Result(property = "number",column = "snumber"),
            @Result(property = "stuName",column = "sname"),
            @Result(property = "courseName",column = "cname"),
            @Result(property = "score",column = "achievement")
    })
    public List<StudentCourseScore> getStudentCourseScoreByNumber(String stuNumber);
 /**
     * 根据学号查询该学生所有课程的成绩
     * @param stuNumber 学生学号
     * @return StudentCourseScore对象集合
     */
    @Select(value = "select s.number as snumber,s.name as sname,c.name as cname,a.achievement " +
            "from t_student s,t_course c,t_achievement a " +
            "WHERE a.student_id=s.id and a.course_id=c.id and s.number=#{stuNumber} ")
    @Results({
            @Result(property = "number",column = "snumber"),
            @Result(property = "stuName",column = "sname"),
            @Result(property = "courseName",column = "cname"),
            @Result(property = "score",column = "achievement")
    })
    public List<StudentCourseScore> getStudentCourseScoreByNumber(String stuNumber);

4.测试查询

在AchieveMentService类中添加如下方法:

//根据学号查询学生课程成绩
    public List<StudentCourseScore> getStudentCourseScoreByNumber(String number){
        return archieveMentMapper.getStudentCourseScoreByNumber(number);
    }
    //根据课程ID查询该课程所有学生的成绩
    public List<StudentCourseScore> getCourseStudentScoreByScoreID(int id){
        return archieveMentMapper.getCourseScoreByCourseID(id);
    }

在ArchievementController控制器中添加如下方法:

/**
     * 根据学号查询该学生所有课程的成绩
     * @param number 学号
     * @return StudentCourseScore对象集合
     */
    @GetMapping("/getStuCourseScore/{number}")
    public List<StudentCourseScore> getStudentCourseScoreByNumber(@PathVariable String number){
        List<StudentCourseScore> result=achieveMentService.getStudentCourseScoreByNumber(number);
        return result;
    }

    /**
     * 根据课程ID查询该课程所有学生的成绩
     * @param id 课程ID
     * @return 所有学生的成绩
     */
    @GetMapping("/getCourseScore/{id}")
    public List<StudentCourseScore> getCourseStudentsScoreByCourseID(@PathVariable int id){
        List<StudentCourseScore> result=achieveMentService.getCourseStudentScoreByScoreID(id);
        return result;
    }

根据学号查询该学生所有课程的成绩,结果如下

根据课程ID查询该课程所有学生的成绩,结果如下:

 

6.5.5 创建前端页面

该页面主要实现根据学生来查询其学习的课程成绩,根据课程名称查询学习该课程的学生的成绩。页面显示结果如下:

在该页面中主要使用的Vue.js前端技术,首先当页面加载时,通过ajax向服务器请求学生、课程的相关信息,并通过下拉列表的方式进行显示,然后,在页面中通过选择相应的学生(课程)后,点击确定按钮进行查询,将查询结果显示在下方的表格中。在做这部分内容之前,首先要建立相关的查询和业务逻辑,

1.建立相关查询

在IStudentMapper中添加如下方法:

//查询所有学生
@Select(value = "select * from t_student s")
@ResultMap("studentMap")
public List<Student> getStudents();

在ICourseMapper中添加如下方法:

//查询所有课程
@Select(value = "select * from t_course")
@ResultMap("courseMap")
public List<Course> getCourses();

2.建立与添加业务层方法

在StudentService中添加如下方法:

//查询所有学生信息
    public List<Student> getStudents(){
        return this.studentMapper.getStudents();
    }

在service包中,新建CourseService类,代码如下:

package com.bluesky.mybatisstudy.service;

import com.bluesky.mybatisstudy.dao.ICourseMapper;
import com.bluesky.mybatisstudy.entity.Course;
import com.bluesky.mybatisstudy.util.DBUtil;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CourseService {
    private ICourseMapper courseMapper= DBUtil.getSession().getMapper(ICourseMapper.class);
    //查询所有课程信息
    public List<Course> getCourses(){
        return courseMapper.getCourses();
    }
}

3.控制器部分

在StudentController中添加如下方法:

//查询所有学生
    @GetMapping("/getStus")
    @ResponseBody
    public List<Student> getStudents(){
        return this.studentService.getStudents();
    }

在controller包下,新建CourseController类,代码如下:

package com.bluesky.mybatisstudy.controller;

import com.bluesky.mybatisstudy.entity.Course;
import com.bluesky.mybatisstudy.service.CourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/course")
public class CourseController {
    @Autowired
    private CourseService courseService;

    @GetMapping("/getCourses")
    @ResponseBody
    public List<Course> getCourses(){
        return this.courseService.getCourses();
    }
}

4.前端页面

前端页面代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>成绩查询</title>

    <link rel="stylesheet" href="/bootstrap.css">
    <script src="/vue.js" type="text/javascript"></script>
    <script src="/vue-resource.min.js" type="text/javascript"></script>
    <script src="/axios.js" type="text/javascript"></script>
    <script src="/jquery.js" type="text/javascript"></script>
    <script src="/bootstrap.js" type="text/javascript"></script>
</head>
<body>
<div id="app" class="container">
    <div class="row">
        <div class="col-md-12"><h2>根据学号查询该学生的所有课程成绩</h2></div>
    </div>
    <div class="row">
        <div class="col-md-12">
            <!--动态加载学生信息-->
            <select name="studentName" id="studentName" v-model="stuID">
                <option v-for="item in stus" :value="item.number">{{item.name}}</option>
            </select>
            <!--按钮-->
            <button @click="getStuCoursesScore">确定</button>
            <table class="table">
                <tr>
                    <td>课程名称</td>
                    <td>成绩</td>
                </tr>
                <tr v-for="item in stuCoursesScore">
                    <td>{{item.courseName}}</td>
                    <td>{{item.score}}</td>
                </tr>
            </table>
        </div>
    </div>
    <!--根据课程查询所有学生的成绩-->
    <div class="row">
        <div class="col-md-12"><h2>根据课程名查询该课程所有学生的成绩</h2></div>
        <!--动态加载课程信息-->
        <select name="courseName" id="courseName" v-model="courseID">
            <option v-for="item in courses" :value="item.id">{{item.name}}</option>
        </select>
        <!--按钮-->
        <button @click="getCourseStusScore">确定</button>
        <table class="table">
            <tr>
                <td>学生学号</td>
                <td>学生姓名</td>
                <td>成绩</td>
            </tr>
            <tr v-for="item in courseStusScore">
                <td>{{item.number}}</td>
                <td>{{item.stuName}}</td>
                <td>{{item.score}}</td>
            </tr>
        </table>
    </div>
</div>
<script>
    var app=new Vue({
        el:'#app',
        data:{
            stus:[],
            courses:[],
            stuCoursesScore:[],
            courseStusScore:[],
            stuID:0,
            courseID:0
        },
        methods:{
            getStuCoursesScore:function(){
                this.$http.get(
                    '/archievement/getStuCourseScore/'+this.stuID
                ).then(function (res) {
                    console.log(res)
                    this.stuCoursesScore=res.body;
                    console.log(this.stuCoursesScore[0]);
                }),function (err) {
                    alert(err);
                };
            },
            getCourseStusScore:function () {
                this.$http.get(
                    '/archievement/getCourseScore/'+this.courseID
                ).then(function(res){
                    this.courseStusScore=res.body;
                }),function (err) {
                    alert(err);
                }
            }
        },
        mounted:function () {
            this.$http.get(
                '/student/getStus'
            ).then(function (res) {
                this.stus=res.body;
            }),function (err) {
                alert(err);
            };
            this.$http.get(
                '/course/getCourses'
            ).then(function (res) {
                this.courses=res.body;
            }),function(err){
                alert(err);
            };
        }
    })
</script>
</body>
</html>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章