mybatis考试
题目:学生选课管理系统(高级版,无事务)
数据库表结构(保持不变)
1.学生表(student)
id(主键, 自增)
name (学生姓名)
gender (性别)
age(年龄)
class_id(班级ID)
2.班级表(class)
id (主键, 自增)
class_name(班级名称)
课程表(course)
id (主键, 自增)
course_name (课程名称)
teacher(授课老师)
3.选课表(student_course)
id (主键, 自增)
student_id(学生ID, 外键)
course_id(课程ID, 外键)
score(成绩)
题目
动态查询学生信息
要求:根据传入的参数动态查询学生信息。参数包括学生姓名(模糊查询)、性别、年龄范围、班级名称。
示例:查询姓名为“张”、性别为“男”、年龄在18到22岁之间、班级名称为“计算机科学与技术1班”的学生。
分页查询所有学生及其选课信息
要求:分页查询所有学生的姓名、班级名称、所选课程名称及成绩,每页显示10条记录
统计每个班级的平均成绩
要求:统计每个班级的平均成绩,并按照平均成绩从高到低排序。
提示:需要关联学生表、班级表和选课表。
批量插入学生选课记录
要求:实现批量插入学生选课记录的功能,确保性能高效。
示例:一次性插入100条选课记录。
查询未选课的学生
要求:查询所有未选任何课程的学生信息。
查询每门课程的选课人数及平均成绩
要求:查询每门课程的选课人数和平均成绩,并按照选课人数从高到低排序。
动态更新学生信息
要求:根据传入的参数动态更新学生信息。参数包括学生ID、姓名、性别、年龄、班级ID,只更新非空的字段。
提示:使用 MyBatis 的动态 SQL
查询成绩排名前10的学生
要求:查询所有学生中,成绩排名前10的学生信息(包括姓名、班级名称、总成绩)。
提示:需要对选课表中的成绩进行汇总和排序。
查询每门课程的最高分、最低分和平均分
要求:查询每门课程的最高分、最低分和平均分,并按照课程名称排序。
二、解答
1.数据库
2.代码
dao
package com.qcby.dao;import com.qcby.entity.StudentCourse;import java.util.List;public interface StudentCourseDao {List<StudentCourse> select();
}
package com.qcby.dao;
import com.qcby.entity.Course;
import com.qcby.entity.Student;
import com.qcby.entity.StudentCourse;
import org.apache.ibatis.annotations.Param;import java.util.List;public interface StudentDao {List<Student> select1(Student student);List<StudentCourse> select2(@Param("offset") int offset, @Param("pageSize") int pageSize);List<Student> select3();int insert(List<StudentCourse> studentCourses);List<Student> select4();List<Course> select5();int update(Student student);List<Student> select6();
}
entity
package com.qcby.entity;public class Class {private Integer id;private String class_name;@Overridepublic String toString() {return "Class{" +"id=" + id +", class_name='" + class_name + '\'' +'}';}public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getClass_name() {return class_name;}public void setClass_name(String class_name) {this.class_name = class_name;}
}
package com.qcby.entity;public class Course {private Integer id;private String course_name;private String teacher;private Double averageScore;private Integer studentCount;@Overridepublic String toString() {return "Course{" +"id=" + id +", course_name='" + course_name + '\'' +", teacher='" + teacher + '\'' +", averageScore=" + averageScore +", studentCount=" + studentCount +'}';}public Double getAverageScore() {return averageScore;}public void setAverageScore(Double averageScore) {this.averageScore = averageScore;}public Integer getStudentCount() {return studentCount;}public void setStudentCount(Integer studentCount) {this.studentCount = studentCount;}public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getCourse_name() {return course_name;}public void setCourse_name(String course_name) {this.course_name = course_name;}public String getTeacher() {return teacher;}public void setTeacher(String teacher) {this.teacher = teacher;}
}
package com.qcby.entity;import java.util.List;public class Student {private Integer id;private String name;private String gender;private Integer age;private Integer minAge;private Integer maxAge;private Integer class_id;private String className;private List<StudentCourse> studentCourses;private Double averageScore;private Double totalScore;@Overridepublic String toString() {return "Student{" +"id=" + id +", name='" + name + '\'' +", gender='" + gender + '\'' +", age=" + age +", minAge=" + minAge +", maxAge=" + maxAge +", class_id=" + class_id +", className='" + className + '\'' +", studentCourses=" + studentCourses +", averageScore=" + averageScore +", totalScore=" + totalScore +'}';}public Double getAverageScore() {return averageScore;}public void setAverageScore(Double averageScore) {this.averageScore = averageScore;}public Double getTotalScore() {return totalScore;}public void setTotalScore(Double totalScore) {this.totalScore = totalScore;}public String getClassName() {return className;}public void setClassName(String className) {this.className = className;}public List<StudentCourse> getStudentCourses() {return studentCourses;}public void setStudentCourses(List<StudentCourse> studentCourses) {this.studentCourses = studentCourses;}public Integer getMinAge() {return minAge;}public void setMinAge(Integer minAge) {this.minAge = minAge;}public Integer getMaxAge() {return maxAge;}public void setMaxAge(Integer maxAge) {this.maxAge = maxAge;}public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getGender() {return gender;}public void setGender(String gender) {this.gender = gender;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}public Integer getClass_id() {return class_id;}public void setClass_id(Integer class_id) {this.class_id = class_id;}
}
package com.qcby.entity;public class StudentCourse{private Long id;private Long studentId;private Long courseId;private String score;private String student_name;private String class_name;private String courseName;private Double maxScore;private Double minScore;private Double avgScore;public Long getId() { return id; }public void setId(Long id) { this.id = id; }public Long getStudentId() { return studentId; }public void setStudentId(Long studentId) { this.studentId = studentId; }public Long getCourseId() { return courseId; }public void setCourseId(Long courseId) { this.courseId = courseId; }public String getScore() { return score; }public void setScore(String score) { this.score = score; }public String getCourseName() { return courseName; }public void setCourseName(String courseName) { this.courseName = courseName; }public Double getMaxScore() { return maxScore; }public void setMaxScore(Double maxScore) { this.maxScore = maxScore; }public Double getMinScore() { return minScore; }public void setMinScore(Double minScore) { this.minScore = minScore; }public Double getAvgScore() { return avgScore; }public void setAvgScore(Double avgScore) { this.avgScore = avgScore; }public String getStudent_name() {return student_name;}public void setStudent_name(String student_name) {this.student_name = student_name;}public String getClass_name() {return class_name;}public void setClass_name(String class_name) {this.class_name = class_name;}@Overridepublic String toString() {return "StudentCourse{" +"id=" + id +", studentId=" + studentId +", courseId=" + courseId +", score='" + score + '\'' +", student_name='" + student_name + '\'' +", class_name='" + class_name + '\'' +", courseName='" + courseName + '\'' +", maxScore=" + maxScore +", minScore=" + minScore +", avgScore=" + avgScore +'}';}
}
mapper
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.qcby.dao.StudentCourseDao"><resultMap id="courseScoreStatsMap" type="com.qcby.entity.StudentCourse"><result property="courseName" column="course_name"/><result property="maxScore" column="max_score"/><result property="minScore" column="min_score"/><result property="avgScore" column="avg_score"/></resultMap><select id="select" resultMap="courseScoreStatsMap">SELECTc.course_name,MAX(sc.score) AS max_score,MIN(sc.score) AS min_score,AVG(sc.score) AS avg_scoreFROMcourse cLEFT JOINstudent_course sc ON c.id = sc.course_idGROUP BYc.course_nameORDER BYc.course_name ASC;</select>
</mapper>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.qcby.dao.StudentDao"><select id="select1" parameterType="com.qcby.entity.Student" resultType="com.qcby.entity.Student">SELECT s.*FROM `student` sLEFT JOIN `class` c ON s.class_id = c.id<where><if test="name != null and name != ''">s.name LIKE CONCAT('%', #{name}, '%')</if><if test="gender != null and gender != ''">AND s.gender = #{gender}</if><if test="minAge != null and maxAge != null">AND s.age between #{minAge} and #{maxAge}</if><if test="className != null and className != ''">AND c.class_name = #{className}</if></where>ORDER BY s.id DESC</select><select id="select2" resultType="com.qcby.entity.StudentCourse">SELECTs.name AS student_name,c.class_name,co.course_name,sc.scoreFROM student sLEFT JOIN class c ON s.class_id = c.idLEFT JOIN student_course sc ON s.id = sc.student_idLEFT JOIN course co ON sc.course_id = co.idLIMIT #{offset}, #{pageSize}</select><select id="select3" resultType="com.qcby.entity.Student">SELECTs.*,AVG(sc.score) AS averageScoreFROMstudent sJOINclass c ON s.class_id = c.idJOINstudent_course sc ON s.id = sc.student_idGROUP BYs.idORDER BYaverageScore DESC;</select><insert id="insert" parameterType="java.util.List">INSERT INTO `student_course` (student_id, course_id, score)VALUES<foreach collection="list" item="item" separator=",">(#{item.studentId}, #{item.courseId}, #{item.score})</foreach></insert><select id="select4" resultType="com.qcby.entity.Student">SELECT s.*FROM `student` sLEFT JOIN `student_course` sc ON s.id = sc.student_idWHERE sc.student_id IS NULL</select><select id="select5" resultType="com.qcby.entity.Course">SELECTc.id,c.course_name,c.teacher,AVG(sc.score) AS averageScore,COUNT(sc.student_id) AS studentCountFROMcourse cLEFT JOINstudent_course sc ON c.id = sc.course_idGROUP BYc.idORDER BYstudentCount DESC;</select><update id="update" parameterType="com.qcby.entity.Student">UPDATE `student`<set><if test="name != null and name != ''">name = #{name},</if><if test="gender != null and gender != ''">gender = #{gender},</if><if test="age != null">age = #{age},</if><if test="class_id != null">class_id = #{class_id}</if></set>WHERE id = #{id}</update><select id="select6" resultType="com.qcby.entity.Student">SELECTs.*,SUM(CAST(sc.score AS DECIMAL(10, 2))) AS totalScoreFROMstudent sLEFT JOINstudent_course sc ON s.id = sc.student_idGROUP BYs.idORDER BYtotalScore DESCLIMIT 10;</select>
</mapper>
配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><settings><!--设置mybatis输出日志--><!--logImpl:表示对日志的控制--><!--STDOUT_LOGGING:将日志输出到控制台上--><setting name="logImpl" value="STDOUT_LOGGING"/><!--懒加载(按需加载、延迟加载)--><!--lazyLoadingEnabled:懒加载是否要启动--><setting name="lazyLoadingEnabled" value="true"/><!--aggressiveLazyLoading:是否按需进行加载(是否加载全部加载,当为true时,懒加载启动也会全部加载,只有为false时才能进行懒加载)--><setting name="aggressiveLazyLoading" value="false"/></settings><environments default="mysql"><environment id="mysql"><!--配置事务的类型,使用本地事务策略--><transactionManager type="JDBC"></transactionManager><!--是否使用连接池 POOLED表示使用链接池,UNPOOLED表示不使用连接池--><dataSource type="POOLED"><property name="driver" value="com.mysql.cj.jdbc.Driver"/><property name="url" value="jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC"/><property name="username" value="root"/><property name="password" value="root"/></dataSource></environment></environments><mappers><mapper resource="mapper/OrderMapper.xml"></mapper><mapper resource="mapper/ProductMapper.xml"></mapper><mapper resource="mapper/StudentMapper.xml"></mapper><mapper resource="mapper/StudentCourseMapper.xml"></mapper></mappers>
</configuration>
测试
import com.qcby.dao.StudentCourseDao;
import com.qcby.entity.StudentCourse;
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 org.junit.After;
import org.junit.Before;
import org.junit.Test;import java.io.IOException;
import java.io.InputStream;
import java.util.List;public class StudentCourseTest {private InputStream in = null;private SqlSession session = null;private StudentCourseDao studentCourseDao = null;@Beforepublic void init() throws IOException {in = Resources.getResourceAsStream("SqlMapConfig.xml");SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);session = factory.openSession();studentCourseDao = session.getMapper(StudentCourseDao.class);}@Afterpublic void destroy() throws IOException {session.close();in.close();}@Testpublic void select() {List<StudentCourse> resultList = studentCourseDao.select();System.out.println("课程成绩统计:");System.out.println("-----------------------------------");for (StudentCourse stats : resultList) {System.out.println("课程名称: " + stats.getCourseName());System.out.println("最高分: " + stats.getMaxScore());System.out.println("最低分: " + stats.getMinScore());System.out.println("平均分: " + stats.getAvgScore());System.out.println("-------------------");}}
}
import com.qcby.dao.StudentDao;
import com.qcby.entity.Course;
import com.qcby.entity.Student;
import com.qcby.entity.StudentCourse;
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 org.junit.After;
import org.junit.Before;
import org.junit.Test;import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;public class StudentTest {private InputStream in = null;private SqlSession session = null;private StudentDao studentDao = null;@Before //前置通知, 在方法执行之前执行public void init() throws IOException {//加载主配置文件,目的是为了构建SqlSessionFactory对象in = Resources.getResourceAsStream("SqlMapConfig.xml");//创建SqlSessionFactory对象SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);//通过SqlSessionFactory工厂对象创建SqlSesssion对象session = factory.openSession();//通过Session创建Dao接口代理对象studentDao = session.getMapper(StudentDao.class);}@After //@After: 后置通知, 在方法执行之后执行 。public void destory() throws IOException {//释放资源session.close();in.close();}@Testpublic void select1() {Student student = new Student();student.setName("张");student.setGender("男");student.setMinAge(18);student.setMaxAge(22);student.setClassName("计算机科学与技术1班");List<Student> students = studentDao.select1(student);for (Student s : students) {System.out.println(s);}}@Testpublic void select2() {int pageNum = 1;int pageSize = 10;int offset = (pageNum - 1) * pageSize;List<StudentCourse> resultList = studentDao.select2(offset, pageSize);System.out.println("第 " + pageNum + " 页学生选课信息:");System.out.println("-----------------------------------");for (StudentCourse studentCourse : resultList) {System.out.println("学生姓名: " + studentCourse.getStudent_name());System.out.println("班级名称: " + studentCourse.getClass_name());System.out.println("课程名称: " + studentCourse.getCourseName());System.out.println("成绩: " + studentCourse.getScore());System.out.println("-------------------");}System.out.println("共查询到 " + resultList.size() + " 条记录");}@Testpublic void select3() {List<Student> resultList = studentDao.select3();for (Student student : resultList) {System.out.println("班级名称: " + student.getClassName());System.out.println("平均成绩: " + student.getAverageScore());System.out.println("-------------------");}}@Testpublic void insert() {List<StudentCourse> studentCourses = new ArrayList<>();for (int i = 0; i < 100; i++) {StudentCourse studentCourse = new StudentCourse();studentCourse.setStudentId((long) ((i % 4) + 1));studentCourse.setCourseId((long) ((i % 8) + 1));studentCourse.setScore("80");studentCourses.add(studentCourse);}int rows = studentDao.insert(studentCourses);System.out.println("插入的学生选课记录数: " + rows);session.commit();}@Testpublic void select4() {List<Student> students = studentDao.select4();for (Student student : students) {System.out.println(student);}}@Testpublic void select5() {List<Course> resultList = studentDao.select5();for (Course course : resultList) {System.out.println("课程名称: " + course.getCourse_name());System.out.println("平均成绩: " + course.getAverageScore());System.out.println("选课人数: " + course.getStudentCount());System.out.println("-------------------");}}@Testpublic void update() {Student student = new Student();student.setId(1);student.setName("三");student.setAge(18);int rows = studentDao.update(student);System.out.println("更新的记录数: " + rows);session.commit();}@Testpublic void select6() {List<Student> resultList = studentDao.select6();System.out.println("成绩排名前10的学生:");System.out.println("-----------------------------------");for (Student student : resultList) {System.out.println("学生姓名: " + student.getName());System.out.println("班级名称: " + student.getClassName());System.out.println("总成绩: " + student.getTotalScore());System.out.println("-------------------");}}
}