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">«</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">»</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>