0% found this document useful (0 votes)
15 views11 pages

实验一 Mybatis框架:学生信息管理应用

This document outlines an experimental report on the Mybatis framework for managing student information. It details the objectives, environment setup, and step-by-step procedures for creating a database, configuring Maven dependencies, and implementing CRUD operations using Mybatis. The report also includes code snippets for database interaction and testing methods for verifying functionality.

Uploaded by

昊元 陈
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views11 pages

实验一 Mybatis框架:学生信息管理应用

This document outlines an experimental report on the Mybatis framework for managing student information. It details the objectives, environment setup, and step-by-step procedures for creating a database, configuring Maven dependencies, and implementing CRUD operations using Mybatis. The report also includes code snippets for database interaction and testing methods for verifying functionality.

Uploaded by

昊元 陈
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

广州商学院

实验报告(第 1 次)

实验名称 Mybatis 框架:学生信息管理应用 实验时间

一、实验目的
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;

set names utf8;


insert into stu values('100000001','尚小云','女','广东广州',1);
insert into stu values('100000002','廖时飞','男','广东梅州',1);
insert into stu values('100000003','宋凌枫','男','湖南郴州',2);
insert into stu values('100000004','刘小纳', '女','广东佛山',2);
create table course
(
cno int primary key,
cname varchar(50) not null,
period int
)ENGINE=InnoDB DEFAULT CHARSET= utf8;

set names utf8;


insert into course values(1,'高等数学',80);
insert into course values(2,'大学英语',70);
insert into course values(3,'数据结构',70);
insert into course values(4,'数据库原理与应用',70);

create table teacher


(
tno int primary key,
tname varchar(24) not null,
tsex char(2) not null,
tel varchar(20)
)ENGINE=InnoDB DEFAULT CHARSET= utf8;

set names utf8;


insert into teacher values(1,'袁怀斌','男','13590909090');
insert into teacher values(2,'杨文远','男','13588888888');
insert into teacher values(3,'周云霞','女','13511118888');

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 names utf8;


insert into sc values('100000001',1,1,80,87,85);
insert into sc values('100000001',2,2,85,75,81);
insert into sc values('100000002',1,1,78,82,80);

-- 恢复客户端默认字符集
SET @@character_set_client = @saved_cs_client;

2、访问 student 数据库


(1)在 IntelliJ IDEA 中新建一个 Maven 项目,取名为 student。
( 2 ) 在 pom.xml 文 件 中 声 明 3 个 依 赖 , mybatis ( MyBatis 框 架 ) 、 mysql-connector-
java(MySQL 驱动)和 junit(单元测试)。若想获得更多的依赖信息或采用不同的版本,可以在 https://
mvnrepository.com 站点中,通过检索关键字获得。
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<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;

public class StudentDBUtil {


private static SqlSessionFactory sqlSessionFactory = null;

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;

public class Student {

PAGE \* MERGEFORMAT1
private String sno;
private String sname;
private String ssex;
private String snative;
private int mno;

// 省略了 getter 和 setter 方法

@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;

public interface StudentMapper1 {


Student selectStudentBySno(String sno);
List<Student> selectStudentBySname(String sname);
Integer insertStudent(Student student);
Integer deleteStudent(String sno);
Integer updateStudent(Student student);

}
// ……

}
(10)注意:StudentMapper1.xml 映射文件中的 mapper 标签中 namespace 的值,
应是接口的全路径:
<mapper
namespace="com.ex02.student.mapper.StudentMapper1">。
在 Mybatis 中,运用接口类进行映射文件的引入:
<mapper
class="com.ex02.student.mapper.StudentMapper1"></mapper>

(11)编写 StudentMapper1Test 方法中的代码,通过由 Mapper 接口生成的代理对象访问数据库。代码


如下:
package com.ex02.student.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;

import static org.junit.Assert.*;

public class StudentMapper1Test {


StudentMapper1 mapper =null;
SqlSession sqlSession =null;
@Before
public void setUp() throws Exception {
Reader resourceAsReader = Resources.getResourceAsReader("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new
SqlSessionFactoryBuilder().build(resourceAsReader);
sqlSession = sqlSessionFactory.openSession();
mapper = sqlSession.getMapper(StudentMapper1.class);
}

@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

You might also like