上一篇在这里springboot-简单的学生选课系统(含mybatis部署和使用)- 1
20230704更新:
代码公开在github了,欢迎下载、点⭐
https://github.com/pxy7896/stu
mapper的修改
现在mybatis已经帮我们生成了简单的model和操作数据库的mapper,那么,如果需要对数据库做其他操作呢?
之前我写过一篇复杂一点的:springboot-mybatis动态操作表格
不过本文只写一个简单的例子,如下图的getCurId。(其他函数都是mybatis自动生成的)
在CourseDao.xml中只要填写红圈中的就好了。其他都是mybatis自动生成的,不需要关心。
需要注意的是,如果返回的是Course对象,那么第一句(例如18行)应该写resultMap=“BaseResultMap”,就是第4~9行说明的、包含这些列的对象;如果返回的不是一个对象,比如是int,string,List< string>这种,要写resultType=“java.lang.Integer” 或者 resultType=“java.lang.String”
service层
service层调用mapper的函数,实现种种功能。
StudentService.java
package com.example.demo.service;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.example.demo.mapper.StudentDao;
import com.example.demo.model.Student;
// 这个注解不要忘了
@Service("StudentService")
public class StudentService {
// Resource自动组装Dao
@Resource
private StudentDao studentDao;
public int addStudent(String name) {
Student student = new Student();
student.setName(name);
this.studentDao.insert(student);
return this.studentDao.getCurId();
}
}
CourseService.java
package com.example.demo.service;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.example.demo.mapper.CourseDao;
import com.example.demo.model.Course;
@Service("CourseService")
public class CourseService {
@Resource
private CourseDao courseDao;
public int addCourse(String name, int weekday, int start) {
Course course = new Course();
course.setName(name);
course.setWeekday(weekday);
course.setStart(start);
this.courseDao.insert(course);
return this.courseDao.getCurId();
}
}
EnrollService.java
package com.example.demo.service;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.demo.mapper.CourseDao;
import com.example.demo.mapper.EnrollDao;
import com.example.demo.mapper.StudentDao;
import com.example.demo.model.Course;
import com.example.demo.model.CourseForShow;
import com.example.demo.model.Enroll;
import com.example.demo.model.Student;
@Service("EnrollService")
public class EnrollService {
@Resource
private EnrollDao enrollDao;
@Resource
private CourseDao courseDao;
// Autowired和Resource有一点区别,不过这里用哪个都行
@Autowired
private StudentDao studentDao;
public boolean enrollCourse(int sid, int cid) {
try {
// check
List<Enroll> enrolled = this.enrollDao.selectBySid(sid);
if (enrolled.size() == 0) {
// student haven't enrolled any course
Enroll enroll = new Enroll();
enroll.setCid(cid);
enroll.setSid(sid);
this.enrollDao.insert(enroll);
return true;
} else {
List<String> times = new ArrayList<String>();
for(Enroll e : enrolled) {
int c = e.getCid();
Course course = this.courseDao.selectByPrimaryKey(c);
String k = String.valueOf(course.getWeekday()) + "-" + String.valueOf(course.getStart());
// no spare time
if (times.contains(k) || c == cid) {
return false;
} else {
times.add(k);
continue;
}
}
// can enroll
Enroll enroll = new Enroll();
enroll.setCid(cid);
enroll.setSid(sid);
this.enrollDao.insert(enroll);
return true;
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public List<Student> queryStudentByCid(int cid) {
List<Enroll> enrolled = this.enrollDao.selectByCid(cid);
List<Student> result = new ArrayList<Student>();
if (enrolled.size() != 0) {
for(Enroll e : enrolled) {
Student s = this.studentDao.selectByPrimaryKey(e.getSid());
if (s != null) {
result.add(s);
}
}
}
return result;
}
public List<CourseForShow> queryCourseBySid(int sid) {
List<Enroll> enrolled = this.enrollDao.selectBySid(sid);
List<CourseForShow> result = new ArrayList<CourseForShow>();
if (enrolled.size() != 0) {
for(Enroll e : enrolled) {
Course c = this.courseDao.selectByPrimaryKey(e.getCid());
if (c != null) {
CourseForShow cfs = new CourseForShow();
cfs.setId(c.getId());
cfs.setName(c.getName());
cfs.setStart(c.getStart());
cfs.setWeekdayByInt(c.getWeekday());
result.add(cfs);
}
}
}
return result;
}
public List<CourseForShow> querySchedule(int sid, int weekday) {
List<Enroll> enrolled = this.enrollDao.selectBySid(sid);
List<CourseForShow> result = new ArrayList<CourseForShow>();
if (enrolled.size() != 0) {
for(Enroll e : enrolled) {
Course c = this.courseDao.selectByPrimaryKey(e.getCid());
if (c != null && c.getWeekday() == weekday) {
CourseForShow cfs = new CourseForShow();
cfs.setId(c.getId());
cfs.setName(c.getName());
cfs.setStart(c.getStart());
cfs.setWeekdayByInt(c.getWeekday());
result.add(cfs);
}
}
}
return result;
}
}
controller层
controller层包含启动类和响应页面请求的函数,这些函数通过调用service层的函数,实现计算,然后组装好结果返回到页面。
DemoApplication.java 启动类:@MapperScan最好写上,不然会报找不到
package com.example.demo;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
@SpringBootApplication()
@MapperScan(basePackages="com.example.demo.mapper")
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
MainController.java
package com.example.demo;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.example.demo.model.Course;
import com.example.demo.model.CourseForShow;
import com.example.demo.model.Student;
import com.example.demo.service.CourseService;
import com.example.demo.service.EnrollService;
import com.example.demo.service.StudentService;
@Controller
public class MainController {
@Resource
private StudentService studentService;
@Resource
private CourseService courseService;
@Resource
private EnrollService enrollService;
// 可以理解成前往templates下的index.html
@RequestMapping("/")
public String toHome() {
return "index";
}
@RequestMapping("/result")
public String toResult() {
return "result";
}
@PostMapping("/addStudent")
public String toAddStudentResult(RedirectAttributes redirectAttributes, @RequestParam("studentName")String studentName) {
//System.out.println("*" + studentName + "*");
// add student ok
int sid = this.studentService.addStudent(studentName);
redirectAttributes.addFlashAttribute("msg", studentName + " has been added successfully! Student id: " + String.valueOf(sid));
return "redirect:/result";
}
@PostMapping("/addCourse")
public String toAddCourseResult(RedirectAttributes redirectAttributes, @RequestParam("courseName")String courseName,
@RequestParam("weekday")String weekday, @RequestParam("start")String start) {
int cid = this.courseService.addCourse(courseName, Integer.parseInt(weekday), Integer.parseInt(start));
redirectAttributes.addFlashAttribute("msg", courseName + " has been added successfully! Course id: " + String.valueOf(cid));
return "redirect:/result";
}
@PostMapping("/enroll")
public String toEnrollResult(RedirectAttributes redirectAttributes, @RequestParam("studentId")String studentId,
@RequestParam("courseId")String courseId) {
boolean flag = this.enrollService.enrollCourse(Integer.parseInt(studentId), Integer.parseInt(courseId));
if (flag) {
redirectAttributes.addFlashAttribute("msg", "Enroll successfully!");
} else {
redirectAttributes.addFlashAttribute("msg", "Student has no spare time!");
}
return "redirect:/result";
}
@PostMapping("/queryStudentsByCid")
public String toQuerryStudentsResult(RedirectAttributes redirectAttributes, @RequestParam("queryCid")String queryCid) {
List<Student> result = this.enrollService.queryStudentByCid(Integer.parseInt(queryCid));
if (result.size() > 0) {
redirectAttributes.addFlashAttribute("resultStudents", result);
redirectAttributes.addFlashAttribute("inputInfo", "Query students by course_id: " + queryCid);
} else {
redirectAttributes.addFlashAttribute("msg", "Query students by course_id: " + queryCid);
redirectAttributes.addFlashAttribute("inputInfo", "Nobody enrolls in this course! ");
}
return "redirect:/result";
}
@PostMapping("/queryCoursesBySid")
public String toQuerryCoursesResult(RedirectAttributes redirectAttributes, @RequestParam("querySid")String querySid) {
List<CourseForShow> result = this.enrollService.queryCourseBySid(Integer.parseInt(querySid));
if (result.size() > 0) {
redirectAttributes.addFlashAttribute("resultCourses", result);
redirectAttributes.addFlashAttribute("inputInfo", "Query courses by student_id: " + querySid);
} else {
redirectAttributes.addFlashAttribute("msg", "Query courses by student_id: " + querySid);
redirectAttributes.addFlashAttribute("inputInfo", " No courses enrolled yet! ");
}
return "redirect:/result";
}
@PostMapping("/querySchedule")
public String toQueryScheduleResult(RedirectAttributes redirectAttributes, @RequestParam("querySSid")String querySSid,
@RequestParam("qWeekday")String qWeekday) {
List<CourseForShow> result = this.enrollService.querySchedule(Integer.parseInt(querySSid), Integer.parseInt(qWeekday));
if (result.size() > 0) {
redirectAttributes.addFlashAttribute("resultCourses", result);
redirectAttributes.addFlashAttribute("inputInfo", "Query schedule for student_id: " + querySSid + " on " + result.get(0).getWeekday());
} else {
redirectAttributes.addFlashAttribute("msg", "Query schedule for student_id: " + querySSid + " on " + result.get(0).getWeekday());
redirectAttributes.addFlashAttribute("inputInfo", " No courses enrolled yet! ");
}
return "redirect:/result";
}
}
页面
index.html
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<title>HOME</title>
<link
href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css"
rel="stylesheet">
<script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/js/bootstrap.min.js" type="text/javascript"></script>
<body>
<!-- add student form -->
<form class="form-horizontal" method="post" th:action="@{/addStudent}" role="form">
<h3> Add student</h6>
<div class="col-sm-1">
<label class="control-label">Name</label>
</div>
<div class="col-sm-2">
<input type="text" class="form-control" name="studentName" placeholder="Jack"/>
</div>
<div class="col-sm-9" >
<button type="submit" class="btn btn-primary">
submit
</button>
</div>
</form>
<br/>
<br/>
<!-- add course form -->
<form class="form-horizontal" method="post" th:action="@{/addCourse}" role="form">
<h3> Add course</h6>
<div>
<div class="col-sm-1">
<label class="control-label">Name</label>
</div>
<div class="col-sm-2">
<input type="text" class="form-control" name="courseName" placeholder="Java"/>
</div>
</div>
<div>
<div class="col-sm-1">
<label class="control-label">Weekday</label>
</div>
<div class="col-sm-2">
<select name="weekday" class="form-control">
<option name="weekday_op" value="0">Monday</option>
<option name="weekday_op" value="1">Tuesday</option>
<option name="weekday_op" value="2">Wednesday</option>
<option name="weekday_op" value="3">Thursday</option>
<option name="weekday_op" value="4">Friday</option>
<option name="weekday_op" value="5">Saturday</option>
<option name="weekday_op" value="6">Sunday</option>
</select>
</div>
</div>
<div>
<div class="col-sm-1">
<label class="control-label">StartTime</label>
</div>
<div class="col-sm-2">
<input type="number" class="form-control" name="start" placeholder="0-24" oninput="if(value<0)value=0;if(value>24)value=24"/>
</div>
</div>
<div>
<button type="submit" class="btn btn-primary">
submit
</button>
</div>
</form>
<br/>
<br/>
<!-- student enroll form -->
<form class="form-horizontal" method="post" th:action="@{/enroll}" role="form">
<h3> Enroll</h6>
<div class="col-sm-1">
<label class="control-label">Student ID</label>
</div>
<div class="col-sm-1">
<input type="number" class="form-control" name="studentId" placeholder="1"/>
</div>
<div class="col-sm-1">
<label class="control-label">Course ID</label>
</div>
<div class="col-sm-1">
<input type="number" class="form-control" name="courseId" placeholder="1"/>
</div>
<div class="col-sm-8" >
<button type="submit" class="btn btn-primary">
submit
</button>
</div>
</form>
<br/>
<br/>
<!-- query students by course_id form -->
<form class="form-horizontal" method="post" th:action="@{/queryStudentsByCid}" role="form">
<h3> Query students by CourseId</h6>
<div class="col-sm-1">
<label class="control-label">Course ID</label>
</div>
<div class="col-sm-2">
<input type="number" class="form-control" name="queryCid" placeholder="1"/>
</div>
<div class="col-sm-9" >
<button type="submit" class="btn btn-primary">
submit
</button>
</div>
</form>
<br/>
<br/>
<!-- query courses by studet_id form -->
<form class="form-horizontal" method="post" th:action="@{/queryCoursesBySid}" role="form">
<h3> Query courses by StudentId</h6>
<div class="col-sm-1">
<label class="control-label">Student ID</label>
</div>
<div class="col-sm-2">
<input type="number" class="form-control" name="querySid" placeholder="1"/>
</div>
<div class="col-sm-9" >
<button type="submit" class="btn btn-primary">
submit
</button>
</div>
</form>
<br/>
<br/>
<!-- query Schedule form -->
<form class="form-horizontal" method="post" th:action="@{/querySchedule}" role="form">
<h3> Query schedule for students</h6>
<div class="col-sm-1">
<label class="control-label">Student ID</label>
</div>
<div class="col-sm-2">
<input type="number" class="form-control" name="querySSid" placeholder="1"/>
</div>
<div class="col-sm-1">
<label class="control-label">Weekday</label>
</div>
<div class="col-sm-2">
<select name="qWeekday" class="form-control">
<option name="qWeekday_op" value="0">Monday</option>
<option name="qWeekday_op" value="1">Tuesday</option>
<option name="qWeekday_op" value="2">Wednesday</option>
<option name="qWeekday_op" value="3">Thursday</option>
<option name="qWeekday_op" value="4">Friday</option>
<option name="qWeekday_op" value="5">Saturday</option>
<option name="qWeekday_op" value="6">Sunday</option>
</select>
</div>
<div class="col-sm-9" >
<button type="submit" class="btn btn-primary">
submit
</button>
</div>
</form>
<br/>
<br/>
</body>
</html>
result.xml
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h3 th:text="${msg}"></h3>
<!-- input info -->
<p th:text="${inputInfo}"></p>
<!-- students list -->
<div>
<table class="table .table-striped table-hover table-condensed">
<tbody>
<tr th:each="item:${resultStudents}">
<td th:text="${item.getId()}"></td>
<td th:text="${item.getName()}"></td>
</tr>
</tbody>
</table>
</div>
<!-- courses list -->
<div>
<table class="table .table-striped table-hover table-condensed">
<tbody>
<tr th:each="item1:${resultCourses}">
<td th:text="${item1.getId()}"></td>
<td th:text="${item1.getName()}"></td>
<td th:text="${item1.getWeekday()}"></td>
<td th:text="${item1.getStart()}"></td>
</tr>
</tbody>
</table>
</div>
<!--th:href="@{/}是跳转回首页-->
<a type="button" class="btn btn-default" th:href="@{/}">
Back
</a>
</body>
</html>
最后的话
以上就是几乎99%的代码了。如果想要完整项目,请关注+私信给我邮箱!