实验三:动态SQL
使用动态SQL进行条件查询、更新以及复杂查询操作。本实验要求利用本章所学知识完成一个学生信息系统,该系统要求实现3个以下功能:
1、多条件查询: 当用户输入的学生姓名不为空,则根据学生姓名进行学生信息的查询; 当用户输入的学生姓名为空,而学生专业不为空,则只根据学生专业进行学生的查询; 当用户输入的学生姓名不为空,且专业不为空,则根据姓名和专业查询学生信息。
当学生姓名和专业都为空,则查询所有学生信息
2、单条件查询:查询出所有id值小于5的学生的信息;
3、学生数据插入:插入三条学生的信息;
创建学生表(tb_student)并输入3条记录,表结构如下:
CREATE TABLE tb_student(
id int(32) PRIMARY KEY AUTO_INCREMENT,
name varchar(50),
major varchar(50),
varchar(16) );
实验步骤
- 1、创建maven项目,在pom.xml文件中配置依赖:MyBatis、mysql、Junit依赖
- 2、新建实体类Student
- 3、在resources下建db.properties、mybatis-config.xml文件。注意要在mybatis-config.xml文件中引入db.properties文件
- 4、在src.main.resources中建包com.mapper,包中建,StudentMapper接口
- 5、在mybatis-config.xml文件中注册StudentMapper.xml文件
- 6、在Test.java目录中创建测试类。
- 7、MybatisUtils
- 8、运行测试方法。

1、创建maven项目,在pom.xml文件中配置依赖:MyBatis、mysql、Junit依赖
<?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>org.example</groupId>
<artifactId>sy2</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
<include>**/*.properties</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.xml</include>
<include>**/*.properties</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
</project>
2、新建实体类Student
package com.pojo;
public class Student {
private Integer id;
private String name;
private String major;
private String sno;
public Student() {
}
public Student(String name, String major, String sno) {
this.name =