实验一 Mybatis框架:学生信息管理应用
实验一 Mybatis框架:学生信息管理应用
实验报告(第 1 次)
一、实验目的
1. 了解 Mybatis 框架的基本工作原理;
2. 熟悉 Mybatis 框架的核心对象;
3. 掌握在 Mybatis 框架中,数据库单个表的访问方法;
4. 要求所有回答的文本格式:五号,宋体、1.5 倍行距,保留原来的单元格背景。
二、实验环境
Windows 10 以上,JDK8.0 以上,idea,Tomcat 8.0 以上
三、实验要求
学生个人独立完成并且必需完成所有实验。
四、实验过程
1、启动 MySQL 数据库服务器,执行下列脚本,创建 student 数据库,做好数据库访问前的准备工作。注意,
sql 脚本放入记事本中保存时,应采用 ansi 编码方式。
-- student 数据库创建示例
create database student character set utf8;
use student;
-- 设计客户端默认字符集
SET @saved_cs_client = @@character_set_client;
SET @@character_set_client = utf8;
-- 含指定引擎和默认字符集
create table stu
(
sno char(9) primary key,
PAGE \* MERGEFORMAT1
sname varchar(30) not null,
ssex char(2) not null,
snative varchar(30),
mno int
)ENGINE=InnoDB DEFAULT CHARSET= utf8;
create table sc
(
sno char(9),
cno int,
tno int,
participation float,
PAGE \* MERGEFORMAT1
final float,
total float,
constraint fk_sc_stu foreign key(sno) references stu(sno),
constraint fk_sc_course foreign key(cno) references course(cno),
constraint fk_sc_teacher foreign key(tno) references teacher(tno),
constraint pk_sc primary key(sno,cno,tno)
)ENGINE=InnoDB DEFAULT CHARSET= utf8;
-- 恢复客户端默认字符集
SET @@character_set_client = @saved_cs_client;
<groupId>com.ex02</groupId>
<artifactId>student</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.9</version>
</dependency>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
PAGE \* MERGEFORMAT1
<version>4.13.2</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>
</dependencies>
</project>
(3)右击 pom.xml 文件,选择 Maven\Reimport 菜单项,启动构件下载,将上述 3 个构件从远程仓库中下
载至本地仓库。
(4)在 src\main\java 目录中,新建 StudentDBUtil 类,用于构造会话对象。代码如下:
package com.ex02.student.utils;
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.Reader;
static {
try {
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
} catch (Exception e) {
e.printStackTrace();
}
}
public static SqlSession getSession() {
return sqlSessionFactory.openSession();
}
}
(5)在 src\main\java 目录中新建 Student 类(即 Java Bean),代码如下(请保持 Java Bean 的属
性和数据表 stu 中字段间的一致):
package com.ex02.student.po;
PAGE \* MERGEFORMAT1
private String sno;
private String sname;
private String ssex;
private String snative;
private int mno;
@Override
public String toString() {
return "Student{" +
"sno='" + sno + '\'' +
", sname='" + sname + '\'' +
", ssex='" + ssex + '\'' +
", snative='" + snative + '\'' +
", mno=" + mno +
'}';
}
}
(6)在 src\main\resources 目录中,新建配置文件 db.properties 和 mybatis-config.xml,内
容如下:
mysql.driver=com.mysql.cj.jdbc.Driver
mysql.url=jdbc:mysql://localhost:3306/student?serverTimezone=GMT%2B8&
characterEncoding=utf8&useUnicode=true&useSSL=false
mysql.username=root
mysql.password=root
<?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="db.properties"/>
<environments default="mysql_student">
<environment id="mysql_student">
<transactionManager type="jdbc" />
<dataSource type="POOLED">
<property name="driver" value="${mysql.driver}" />
<property name="url" value="${mysql.url}" />
<property name="username" value="${mysql.username}" />
<property name="password" value="${mysql.password}" />
</dataSource>
</environment>
</environments>
<mappers>
PAGE \* MERGEFORMAT1
<mapper resource="mapper/StudentMapper.xml"/>
</mappers>
</configuration>
(7)在 src\main\resources\mapper 目录中,新建 StudentMapper.xml 文件,在文件中编写对
stu 表进行查询、插入、删除及更新等操作的配置信息。内容如下:
<?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.ex02.student.po.Student">
<select id="selectStudentBySno" parameterType="String"
resultType="com.ex02.student.po.Student">
select * from stu where sno=#{sno};
</select>
<select id="selectStudentBySname" parameterType="String"
resultType="com.ex02.student.po.Student">
select * from stu where sname like concat('%',#{sname},'%');
</select>
<insert id="insertStudent" parameterType="com.ex02.student.po.Student">
insert into stu(sno,sname,ssex,snative,mno)
values(#{sno},#{sname},#{ssex},#{snative},#{mno});
</insert>
<delete id="deleteStudent" parameterType="String">
delete from stu where sno=#{sno}
</delete>
<update id="updateStudent" parameterType="com.ex02.student.po.Student">
update stu set sname=#{sname},ssex=#{ssex},snative=#{snative},mno=#{mno}
where sno=#{sno}
</update>
</mapper>
(8)在 src\test\java 中,新建 StudentTest 类,在 studentTest 方法中编写代码,测试对 stu 表的查
询、插入、删除和更新等操作。
package com.ex02.student;
import com.ex02.student.po.Student;
import com.ex02.student.utils.StudentDBUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class StudentTest {
SqlSession sqlSession = StudentDBUtil.getSession();
int count = -1;
Student student;
PAGE \* MERGEFORMAT1
@Test
public void findStudentBySno() {
// 精确查询测试
Student student =
sqlSession.selectOne("com.ex02.student.po.Student.selectStudentBySno", "100000001");
System.out.println(student);
}
@Test
public void findStudentAll() {
// 模糊查询测试
List<Student> list =
sqlSession.selectList("com.ex02.student.po.Student.selectStudentBySname", "小");
for (Student stu : list)
System.out.println(stu);
}
@Test
public void deleteStudent() {
// 删除记录测试
String snoToDelete = "100000009"; // 替换为要删除的学号
count = sqlSession.delete("com.ex02.student.po.Student.deleteStudent",
snoToDelete);
sqlSession.commit();
System.out.println("成功删除了" + count + "条记录。");
}
@Test
public void updateStudent() {
// 更新记录测试
student = new Student();
student.setSno("100000001"); // 替换为要更新的学号
student.setSname("张伟");
student.setSsex("男");
student.setSnative("广东广州");
student.setMno(3);
count = sqlSession.update("com.ex02.student.po.Student.updateStudent",
student);
sqlSession.commit();
System.out.println("成功更新了" + count + "条记录。");
}
}
PAGE \* MERGEFORMAT1
( 9 ) 在 src\main\java 目 录 中 , 定 义 接 口 StudentMapper1 , 接 口 的 方 法 与
StudentMapper1.xml 文件中的各查询 statement 的 id 值对应。部分代码如下:
package com.ex02.student.mapper;
import com.ex02.student.po.Student;
import java.util.List;
}
// ……
}
(10)注意:StudentMapper1.xml 映射文件中的 mapper 标签中 namespace 的值,
应是接口的全路径:
<mapper
namespace="com.ex02.student.mapper.StudentMapper1">。
在 Mybatis 中,运用接口类进行映射文件的引入:
<mapper
class="com.ex02.student.mapper.StudentMapper1"></mapper>
import com.ex02.student.po.Student;
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.Reader;
PAGE \* MERGEFORMAT1
import java.util.List;
@After
public void tearDown() throws Exception {
}
@Test
public void selectStudentBySno() {
Student student = mapper.selectStudentBySno("100000001");
System.out.println(student);
}
@Test
public void selectStudentBySname() {
List<Student> students = mapper.selectStudentBySname("刘");
for (Student student : students) {
System.out.println(student);
}
}
@Test
public void insertStudent() {
// 插入一个新的学生
Student newStudent = new Student();
newStudent.setSno("100000010");
newStudent.setSname("张三");
newStudent.setSsex("男");
newStudent.setSnative("北京");
newStudent.setMno(1);
PAGE \* MERGEFORMAT1
int result = mapper.insertStudent(newStudent);
sqlSession.commit(); // 提交事务
System.out.println("成功插入了" + result + "条记录。");
}
@Test
public void deleteStudent() {
// 删除学生
int result = mapper.deleteStudent("100000010");
sqlSession.commit(); // 提交事务
System.out.println("成功删除了" + result + "条记录。");
}
@Test
public void updateStudent() {
// 更新学生信息
Student student = mapper.selectStudentBySno("100000009");
if (student != null) {
student.setSname("李四");
int result = mapper.updateStudent(student);
sqlSession.commit(); // 提交事务
System.out.println("成功更新了" + result + "条记录。");
} else {
System.out.println("未找到学生,无法更新。");
}
}
}
// sqlSession.close();
}
}
(12)填写接口中所有方法测试的结果截图。
1.
PAGE \* MERGEFORMAT1
2.
PAGE \* MERGEFORMAT1