Mybatis的综合案例-学生信息查询系统 用于校验是否真正学习掌握了动态SQL

Mybatis的综合案例-学生信息查询系统

需求一:当用户输入的学生姓名不为空,则只根据学生信息进行查询;
当用户输入的学生姓名为空,且专业不为空,那么就根据学生专业进行学生的查询

需求二:查询所有id值小于5的学生信息


1.搭建项目环境:

​ 往pom中写入依赖引入,引入我们所需要的各个架包:Mybatis3.5.2、Mysql8.0、Junit4.12、log4j1.2.17、(若是无法使用maven方式导入的话,我会带上项目需要的所有离线jar架包,可以自行导入到自己项目的lib下进行安装)


   <dependencies>
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatisartifactId>
            <version>3.5.2version>
        dependency>
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>8.0.11version>
        dependency>
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.12version>
            
            <scope>compilescope>
        dependency>
        <dependency>
            <groupId>log4jgroupId>
            <artifactId>log4jartifactId>
            <version>1.2.17version>
        dependency>
    dependencies>
    <build>
        <resources>
            <resource>
                <directory>src/main/javadirectory>
                <includes>
                    <include>**/*.propertiesinclude>
                    <include>**/*.xmlinclude>
                includes>
                <filtering>truefiltering>
            resource>
        resources>
    build>

2.数据库准备

​ 我们这次的项目是学生信息查询系统,因此我们需要准备名为:studentinfoselectsystem的数据库(也可缩写为studentiss,命名规则:项目名称要全小写),其中的表为:dm_student

​ SQL语句如下(若是不能使用,也可以在文章头下载数据库文件sql):

Create table dm_student(
id int(32) PRIMARY KEY AUTO_INCREMENT,
name varchar(50),
major varchar(50),
sno varchar(16)
);

insert into dm_student VALUES('1','Stevedash','数学','100');
insert into dm_student VALUES('2','Steve','语文','100');
insert into dm_student VALUES('3','Kdash','英语','100');
insert into dm_student VALUES('4','wgd','数学','80');
insert into dm_student VALUES('5','dxm','语文','90');
insert into dm_student VALUES('6','god','英语','60');

3.配置文件准备

​ 准备好所有的配置文件:mybatis-config.xml(mybatis的核心配置文件)、db.properties(jdbc链接数据库配置文件)、log4j.propertie(log4j日志导出配置文件)

在这里插入图片描述

具体代码如下:

mybatis-config.xml

DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    
    
    <properties resource="db.properties"/>
    
    <typeAliases>
        <package name="pojo"/>
    typeAliases>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            dataSource>
        environment>
    environments>
    
    <mappers>
        <mapper resource="mapper/StudentMapper.xml"/>
    mappers>
configuration>
db.properties
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/studentinfoselectsystem?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false
username=root
password=root
log4j.propertie
###\u6839logger\u8BBE\u7F6E###
log4j.rootLogger = debug,console,file

### 
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.Target = System.out
log4j.appender.console.layout = org.apache.log4j.PatternLayout
log4j.appender.console.Threshold = DEBUG 
log4j.logger.java.sql.Statement=debug 
log4j.appender.console.layout.ConversionPattern = [%p] %d %c - %m%n

###
log4j.appender.file = org.apache.log4j.DailyRollingFileAppender
###
log4j.appender.file.File = D:/log/web.log
log4j.appender.file.Append = true
log4j.appender.file.Threshold = warn 
log4j.appender.file.layout = org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern = [%p] %d %c - %m%n


4.编写pojo类

​ pojo(普通java对象),创建出持久化类Student与数据库dm_student进行映射关联,要在类中声明好变量和数据库表中的字段一一对应,并且生成getter和setter方法。

Student.java具体代码如下:
package pojo;

public class Student {
    private int id;//对应数据库字段id
    private String name;//姓名 对应数据库字段name
    private String major;//专业 对应数据库字段major
    private String sno;学号 对应数据库字段sno

    //生成getter和setter方法
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getMajor() {
        return major;
    }

    public void setMajor(String major) {
        this.major = major;
    }

    public String getSno() {
        return sno;
    }

    public void setSno(String sno) {
        this.sno = sno;
    }
    /*
    重写toString()方法,让其变成输出我们想要的信息,
    方便我们检查测试功能需求是否满足
    */
    @Override
    public String toString(){
        return "Student{"+"id="+id+",name="+name+",major="+major+",sno="+sno+"}";
    }
}

5.编写StudentMapper.xml

​ 在resources新建一个package:mapper,在mapper 包下新建一个StudentMapper.xml。

①StudentMapper.xml具体代码如下:

DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="mapper.StudentMapper">

    <select id="selectStudentByNameOrMajor" parameterType="Student" resultType="Student">
          select * from dm_student where 1=1
              <choose>
                  <when test="name!=null and name!=''">
                    and name=#{name}
                  when>
                  <when test="major!=null and major!=''">
                      and major=#{major}
                  when>
                  <otherwise>
                     and  sno is not null
                  otherwise>
              choose>

    select>

    <select id="selectAllIdSmallThanNumber" parameterType="int" resultType="Student">
        SELECT * FROM dm_student WHERE id IN
        <foreach item="id" collection="list" open="(" separator="," close=")">
            #{id}
        foreach>
    select>


    <insert id="addStudent" parameterType="Student">
        insert into dm_student(id,name,marjor,sno) values(#{id},#{name},#{marjor},#{sno})
    insert>

    <delete id="deleteStudent" parameterType="Student">
        delete from dm_student where id = #{id}
    delete>


    <select id="getStudentByList" resultType="Student">
        select * from dm_student where id in
        <foreach collection="list" item="id" open="(" separator="," close=")">
            #{id}
        foreach>
    select>

    <select id="selectByIdLessThan" parameterType="int" resultType="Student">
    SELECT * FROM dm_student WHERE id < #{id}
    select>


mapper>
②编写测试类StudentTest.java
package Test;

import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;
import org.junit.jupiter.api.Test;
import pojo.Student;
import utils.MyBatisUtil;

import java.util.ArrayList;
import java.util.List;


class StudentTest {
    private Logger logger= Logger.getLogger(StudentTest.class);
    /*
        当用户输入的学生姓名不为空,则只根据学生信息进行查询;
        当用户输入的学生姓名为空,且专业不为空,那么就根据学生专业进行学生的查询
    */
    @Test
    void selectByNameOrMajor() {
        SqlSession session= MyBatisUtil.createSqlSession();
        Student student=new Student();
        //student.setName("SteveDash");
        //student.setMajor("数学");
        List<Student> list=session.selectList("selectStudentByNameOrMajor",student);

        for (Student student1:list){
            logger.info(student1.toString());
        }

    }

    /*
        查询所有id值小于5的学生信息
    */
    @Test
    void selectAllIdSmallThanNumber() {
        SqlSession session= MyBatisUtil.createSqlSession();
        List<Integer> intList=new ArrayList<Integer>();
        for(int i=1;i<5;i++){
            intList.add(i);
        }

        List<Student> list=session.selectList("selectAllIdSmallThanNumber",intList);

        for (Student student1:list){
            logger.info(student1.toString());
        }

    }


     /*
      查询所有id值小于number的学生信息
     */
    @Test
    void selectAllIdNumber() {
        SqlSession session= MyBatisUtil.createSqlSession();
        List<Student> list=session.selectList("selectByIdLessThan",5);
        for (Student student1:list){
            logger.info(student1.toString());
        }

    }
}

反思:需求二是不是可以更改成自己想输入那个数字就输入哪个数字去查询小于该数字的学生信息?

那么最简单的编写SQl语句就是这个了吧?

在这里插入图片描述

但是你会发现,不可以 <报错了,是因为它识别不出来,所以我们得用其他字符来替代

<select id="selectByIdLessThan" parameterType="int" resultType="Student">
    SELECT * FROM dm_student WHERE id < #{id}
    select>

解释一下这串代码: