IDEA创建Maven工程使用Mybatis框架,对单表进行简单的增删改查的操作

搭建环境

搭建数据库表

使用的是MySQL数据库。新建名为task的数据库,在task数据库中新建名为student的表。在表中适当添加数据。创建表和添加数据的SQL语句如下所示。

SET FOREIGN_KEY_CHECKS=0;
--创建表
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
  `sid` varchar(40) NOT NULL DEFAULT '' COMMENT 'UUID,唯一标识',
  `id` int(10) DEFAULT NULL COMMENT '学生编号',
  `name` varchar(20) DEFAULT NULL COMMENT '学生姓名',
  `password` varchar(20) DEFAULT NULL COMMENT '学生密码',
  `age` int(3) unsigned DEFAULT NULL COMMENT '学生年龄',
  `sex` varchar(2) DEFAULT NULL COMMENT '学生性别',
  PRIMARY KEY (`sid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--在表中添加数据
INSERT INTO `student` VALUES ('9577f4badff2443e9e67bcc63b640341', '1005', 'KID', '12345', '20', '女');
INSERT INTO `student` VALUES ('9577f4badff2443e9e67bcc63b640342', '1001', '张三', '1235', '12', '女');
INSERT INTO `student` VALUES ('c93bbe3c69ed4cbeb07a2a06ccb97612', '1002', '李四', '1235', '30', '男');
INSERT INTO `student` VALUES ('db7d44de97e1418d95fd73a77b9a9b0c', '1003', '王五', '1235', '12', '女');
INSERT INTO `student` VALUES ('fjakslfk349rhrksar4', '1004', '赵六', '1235', '25', '男');

创建成功以后的数据表。

创建Maven工程

使用IDEA创建一个Maven工程。

新建项目,选择创建Maven工程,选择自己电脑中的JDK,点击下一步。

 输入项目名称,选择该项目存放的地址,最后点击Finish,完成Maven项目的创建。

引入Mybatis框架

百度搜索Mybatis,进入Myabtis的官方网站。mybatis – MyBatis 3 | 简介https://mybatis.org/mybatis-3/zh/index.html点击左侧的入门,右侧的依赖代码放在项目pom.xml文件中,依赖代码必须放在 <dependencies></dependencies> 中。

也可以在Maven仓库中获取Mybatis的依赖代码。原理和获取MySQL数据库的JDBC相似。Maven Repository: org.mybatis » mybatis » 3.5.7 (mvnrepository.com)https://mvnrepository.com/artifact/org.mybatis/mybatis/3.5.7除此之外,还需要引入MySQL数据库的JDBC依赖。可以在Maven仓库中获取MySQL数据库的JDBC依赖代码。Maven Repository: Search/Browse/Explore (mvnrepository.com)https://mvnrepository.com/在Maven仓库中直接搜索MySQL,选择打开一个MySQL类型,选择需要的MySQL版本,将依赖代码粘贴在pom.xml文件中即可。

 

为了方便测试,我们还需要添加Junit依赖,添加Junit依赖的方法和添加MySQL依赖的方法类似。

Maven Repository: junit » junit » 4.13.2 (mvnrepository.com)https://mvnrepository.com/artifact/junit/junit/4.13.2在运行时,可能会出现文件资源获取失败的问题,可以直接将下面的代码复制在项目的pom.xml配置文件中即可。极力建议将下面的代码放在每个Maven项目中。

    <!--在build中配置resources,来防止资源导出失败的问题-->
    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>

 本项目所用到的的所有依赖和配置代码。pom.xml文件中的代码。

<?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>Task2</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>16</maven.compiler.source>
        <maven.compiler.target>16</maven.compiler.target>
    </properties>

    <!--添加依赖代码-->
    <dependencies>

        <!--添加MySQL数据库的JDBC依赖-->
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.26</version>
        </dependency>

        <!--添加Mybatis框架依赖-->
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.7</version>
        </dependency>

        <!--添加Junit单元测试的依赖-->
        <!-- https://mvnrepository.com/artifact/junit/junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

    <!--在build中配置resources,来防止资源导出失败的问题-->
    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>

</project>

添加完依赖后,可能会爆红,需要点击右上角的刷新按钮,刷新本地资源,爆红问题即可解决。

需要在resoutces包下创建mybatis-config.xml文件,文件名可以是其他的,但是最好和官方文件名相符;将官方给出的配置文件代码复制粘贴到自己新创建的配置文件中。其中,<mapper></mapper>中的路径我们后面会进行更改。

 

<?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>
    <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="org/mybatis/example/BlogMapper.xml"/>
    </mappers>
</configuration>

还需要对Mybatis进行简单的配置,提供连接数据库的信息。

我们这里使用外部资源,对Mybatis连接数据库的信息进行配置。

需要先在resources文件夹下创建一个config.properties资源文件。

在新创建的config.properties资源文件中,添加自己数据库的信息。

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/task?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
username=root
password=

 

在mybatis-config.xml配置文件中引入外部资源。我们不需要更改外部资源中的信息,直接引入即可,可以使用自闭合标签。

    <!--引入外部配置文件-->
    <properties resource="config.properties"/>

编写代码

编写工具类

在java包下创建如图所示的包目录。包结构采用MVC规范,将调用和实现分离。controller存放控制层代码,dao包中存放数据库工具类,pojo包中存放Student实例类,service包中存放业务接口和相对应的配置文件。(现在看不懂不要紧,下面都会讲到)

在dao包中创建MyBatisUtil.java工具类,可以方便后面的使用。我们需要在MyBatisUtil.java文件中,先创建SqlSessionFactoryBuilder对象,然后再通过SqlSessionFactoryBuilder对象获取SqlSessionFactory对象,再通过SqlSessionFactory对象获取SqlSession对象。SqlSession 提供了在数据库执行 SQL 命令所需的所有方法,可以通过SqlSession对象去执行映射的SQL语句。

SqlSessionFactory,顾名思义是SqlSession的创建工厂。可以使用SqlSessionFactory对象的openSession()方法获取SqlSession对象。其中openSession()方法可以传递传递参数,参数为true时,MyBatis可以自动提交事务,在执行增删改操作的时候不需要再进行提交事务的操作。

我们这里对官方的写法进行简单的修改,创建静态的SqlSessionFactory对象和静态的getSqlSession方法,通过调用一个静态的getSqlSession方法就可以获取SqlSession对象。这样MyBatis的工具类已经写好了,后面可以直接使用getSqlSession()方法获取SqlSession对象了。

package com.kid.dao;

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.IOException;
import java.io.InputStream;

public class MyBatisUtil {

    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static SqlSession getSqlSession() {
        //修改数据库中的数据(增删改)必须提交事务,否则数据不会保存到数据库
        //openSession(true)中的参数,true自动提交事务
        return sqlSessionFactory.openSession(true);
    }

}

创建实例类

再pojo包中创建Student.java类,该类中的属性需要和数据库中的属性相对应,并且需要按照JavaBean的规范进行创建(私有属性,共有接口)。需要注意,数据库中的varchar类型映射到Java中为String类型。

package com.kid.pojo;

public class Student {
    private String sid;//UUID,唯一标识
    private int id;//学生编号
    private String name;//学生姓名
    private String password;//登录密码
    private int age;//年龄
    private String sex;//性别

    public Student(String sid, int id, String name, String password, int age, String sex) {
        this.sid = sid;
        this.id = id;
        this.name = name;
        this.password = password;
        this.age = age;
        this.sex = sex;
    }

    public String getSid() {
        return sid;
    }

    public void setSid(String sid) {
        this.sid = sid;
    }

    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 getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    @Override
    public String toString() {
        return "Student{" +
                "sid='" + sid + '\'' +
                ", id=" + id +
                ", name='" + name + '\'' +
                ", password='" + password + '\'' +
                ", age=" + age +
                ", sex='" + sex + '\'' +
                '}';
    }
}

创建业务接口

使用Mybatis时,需要先创建业务接口,然后在xml配置文件中进行映射相关的SQL语句。

在com.kid.service包下,先创建StudentService接口处理学生的具体业务。接口中的方法可以根据自己的需要进行更改。

package com.kid.service;

import com.kid.pojo.Student;

import java.util.List;

public interface StudentService {
    //增加学生
    int insertStudent(Student student);

    //删除学生
    int deleteStudentBySid(String sid);

    int deleteStudentById(int id);

    int deleteStudentByName(String name);

    int deleteStudentByAge(int age);

    int deleteStudentBySex(String sex);

    //修改学生信息
    int updateStudent(Student student);

    //查找学生
    List<Student> getStudentAll();

    List<Student> getStudentBySid(String sid);

    List<Student> getStudentById(int id);

    List<Student> getStudentByName(String name);

    List<Student> getStudentByAge(int age);

    List<Student> getStudentBySex(String sex);
}

对业务接口进行映射 

在com.kid.service包下创建StudentServiceImp.xml配置文件,在该配置文件中对StudentService接口中的方法进行映射。

需要在配置文件中,通过命名空间(namespace)将配置文件和接口进行绑定,需要给namespace提供接口的全限定类名。

对查找方法进行映射。

 StudentService接口中查询语句的映射方法。需要使用<select></select>标签,标签中的属性一般会使用id、parameterType和resultType三个。id就是将该标签和接口中需要映射的方法进行绑定,id的值必须是接口中的方法名;parameterType就是接口中方法需要的参数类型;resultType就是接口中方法的返回值类型,如果返回值是List集合,则需要写List集合中元素的类型。

对增加、删除、修改的方法进行映射。

增加、删除、修改的标签属性十分相似。常用的有id和parameterType两个属性:id就是将该标签和接口中需要映射的方法进行绑定,id的值必须是接口中的方法名;parameterType属性一般可以省略,MyBatis可以自动推断出具体传入语句的参数类型。

StudentServiceImp.xml配置文件中的映射代码。

<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.kid.service.StudentService">

    <!--添加学生信息-->
    <insert id="insertStudent" parameterType="com.kid.pojo.Student">
        insert into task.student (sid, id, name, password, age, sex)
        values (#{sid}, #{id}, #{name}, #{password}, #{age}, #{sex})
    </insert>

    <!--删除学生信息-->
    <!--根据Sid删除学生-->
    <delete id="deleteStudentBySid" parameterType="String">
        delete
        from task.student
        where sid = #{sid}
    </delete>
    <!--根据id删除学生-->
    <delete id="deleteStudentById" parameterType="int">
        delete
        from task.student
        where id = #{id}
    </delete>
    <!--根据name删除学生-->
    <delete id="deleteStudentByName" parameterType="String">
        delete
        from task.student
        where name = #{name}
    </delete>
    <!--根据age删除学生-->
    <delete id="deleteStudentByAge" parameterType="int">
        delete
        from task.student
        where age = #{age}
    </delete>
    <!--根据sex删除学生-->
    <delete id="deleteStudentBySex" parameterType="String">
        delete
        from task.student
        where sex = #{sex}
    </delete>

    <!--修改学生信息-->
    <update id="updateStudent" parameterType="com.kid.pojo.Student">
        update task.student
        set sid = #{sid} ,id=#{id}, name =#{name}, password=#{password}, age=#{age}, sex=#{sex}
        where sid=#{sid};
    </update>

    <!--查找学生信息-->
    <!--查找所有学生-->
    <select id="getStudentAll" resultType="com.kid.pojo.Student">
        select *
        from task.student
    </select>
    <!--根据sid查找学生-->
    <select id="getStudentBySid" parameterType="String" resultType="com.kid.pojo.Student">
        select *
        from task.student
        where sid = #{sid}
    </select>
    <!--根据id查找学生-->
    <select id="getStudentById" parameterType="int" resultType="com.kid.pojo.Student">
        select *
        from task.student
        where id = #{id}
    </select>
    <!--根据name查找学生-->
    <select id="getStudentByName" parameterType="String" resultType="com.kid.pojo.Student">
        select *
        from task.student
        where name = #{name}
    </select>
    <!--根据age查找学生-->
    <select id="getStudentByAge" parameterType="int" resultType="com.kid.pojo.Student">
        select *
        from task.student
        where age = #{age}
    </select>
    <!--根据sex查找学生-->
    <select id="getStudentBySex" parameterType="String" resultType="com.kid.pojo.Student">
        select *
        from task.student
        where sex = #{sex}
    </select>

</mapper>

我们还需要在mybatis-config.xml中进行注册,告诉MyBatis去哪里找接口对应的SQL语句。我们在mybatis-config.xml文件进行注册StudentServiceImp.xml。

在mybats-config.xml文件中,插入以下配置代码。

<mappers>
    <mapper resource="com/kid/service/StudentServiceImp.xml"/>
</mappers>

添加控制层

通过控制层调用业务层的接口,从而实现具体的业务。控制层对于小项目来说没什么作用可以忽略不计,但是对于复杂的项目来说,控制层可以使得代码更清晰,所以,在练习的时候尽量按照规范来编写代码结构。

在controller包下创建StudentController.java类。我们在StudentService接口中,写了很多根据不同参数增删改查的方法,为了方便调用,我们在StudentController类中,将所有方法统归为4类,即增加、删除、修改、查找4种方法,通过传入参数的形式区分具体调用的是什么方法。具体流程为:先使用MyBatisUtil类获取SqlSession对象,再通过SqlSession对象获取StudentService的对象,通过StudentService对象调用其方法,需要注意的是,要通过SqlSession对象关闭连接。具体代码如下所示。

package com.kid.controller;

import com.kid.dao.MyBatisUtil;
import com.kid.pojo.Student;
import com.kid.service.StudentService;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class StudentController {

    /**
     * 重载,没有参数就查询所有学生信息
     *
     * @return 返回所有学生的信息列表
     */
    public List<Student> selectStudent() {
        return getStudentAll();
    }

    /**
     * 重载,根据参数,选择调用查找学生的方法
     *
     * @param object 查找学生需要的参数的值
     * @param str    查找学生需要的参数的类型,Sid,Id,Name,Sex,Age
     * @return
     */
    public List<Student> selectStudent(Object object, String str) {
        List<Student> list = null;

        if (str == null) {
            list = getStudentAll();
        } else {

            switch (str) {
                case "sid":
                case "Sid":
                    list = getStudentBySid((String) object);
                    break;
                case "id":
                case "Id":
                    list = getStudentById((int) object);
                    break;
                case "name":
                case "Name":
                    list = getStudentByName((String) object);
                    break;
                case "age":
                case "Age":
                    list = getStudentByAge((int) object);
                    break;
                case "sex":
                case "Sex":
                    list = getStudentBySex((String) object);
                    break;
            }
        }

        return list;
    }

    /**
     * 查找所有学生信息
     *
     * @return 返回所有学生的信息列表
     */
    public List<Student> getStudentAll() {
        List<Student> list = null;
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        StudentService StudentService = sqlSession.getMapper(StudentService.class);
        list = StudentService.getStudentAll();
        sqlSession.close();
        return list;
    }

    /**
     * 根据Sid查找学生信息
     *
     * @param sid 学生唯一标识
     * @return 返回符合查询条件的学生信息列表
     */
    public List<Student> getStudentBySid(String sid) {
        List<Student> list = null;
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        StudentService StudentService = sqlSession.getMapper(StudentService.class);
        list = StudentService.getStudentBySid(sid);
        sqlSession.close();
        return list;
    }

    /**
     * 根据学生Id学号查询学生信息
     *
     * @param id 学生的学号
     * @return 返回符合查询条件的学生信息列表
     */
    public List<Student> getStudentById(int id) {
        List<Student> list = null;
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        StudentService StudentService = sqlSession.getMapper(StudentService.class);
        list = StudentService.getStudentById(id);
        sqlSession.close();
        return list;
    }

    /**
     * 根据学生姓名查询学生信息
     *
     * @param name 学生姓名
     * @return 返回符合查询条件的学生信息列表
     */
    public List<Student> getStudentByName(String name) {
        List<Student> list = null;
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        StudentService StudentService = sqlSession.getMapper(StudentService.class);
        list = StudentService.getStudentByName(name);
        sqlSession.close();
        return list;
    }

    /**
     * 根据学生年龄查询学生信息
     *
     * @param age 学生年龄
     * @return 返回符合查询条件的学生信息列表
     */
    public List<Student> getStudentByAge(int age) {
        List<Student> list = null;
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        StudentService StudentService = sqlSession.getMapper(StudentService.class);
        list = StudentService.getStudentByAge(age);
        sqlSession.close();
        return list;
    }

    /**
     * 根据学生性别查询学生信息
     *
     * @param sex 学生性别
     * @return 返回符合查询条件的学生信息列表
     */
    public List<Student> getStudentBySex(String sex) {
        List<Student> list = null;
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        StudentService StudentService = sqlSession.getMapper(StudentService.class);
        list = StudentService.getStudentBySex(sex);
        sqlSession.close();
        return list;
    }

    /**
     * 根据提供的学生对象,添加学生信息
     *
     * @param student 学生对象
     * @return 插入成功返回真,否则返回假
     */
    public boolean insertStudent(Student student) {
        boolean result = false;
        SqlSession session = MyBatisUtil.getSqlSession();
        StudentService StudentService = session.getMapper(StudentService.class);
        result = StudentService.insertStudent(student) > 0 ? true : false;
        session.close();
        return result;
    }

    /**
     * 根据参数,选择调用删除学生信息的方法
     *
     * @param object 需要的参数值
     * @param str    删除学生的依据,根据Sid,Id,Name,Sex,Age
     * @return 删除成功返回真,否则返回假
     */
    public boolean deleteStudent(Object object, String str) {
        boolean flag = false;

        switch (str) {
            case "sid":
            case "Sid":
                flag = deleteStudentBySid((String) object);
                break;
            case "id":
            case "Id":
                flag = deleteStudentById((int) object);
                break;
            case "name":
            case "Name":
                flag = deleteStudentByName((String) object);
                break;
            case "age":
            case "Age":
                flag = deleteStudentByAge((Integer) object);
                break;
            case "sex":
            case "Sex":
                flag = deleteStudentBySex((String) object);
                break;
        }
        return flag;
    }

    /**
     * 根据学生Sid删除学生
     *
     * @param sid
     * @return
     */
    public boolean deleteStudentBySid(String sid) {
        boolean result;
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        StudentService StudentService = sqlSession.getMapper(StudentService.class);
        result = StudentService.deleteStudentBySid(sid) > 0 ? true : false;
        sqlSession.close();
        return result;
    }

    /**
     * 根据学生编号删除学生
     *
     * @param id 学生的Id编号
     * @return 删除成功返回真, 否则返回假
     */
    public boolean deleteStudentById(int id) {
        boolean result;
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        StudentService StudentService = sqlSession.getMapper(StudentService.class);
        result = StudentService.deleteStudentById(id) > 0 ? true : false;
        sqlSession.close();
        return result;
    }

    /**
     * 根据名字删除学生
     *
     * @param name 学生姓名
     * @return 删除成功返回真, 否则返回假
     */
    public boolean deleteStudentByName(String name) {
        boolean result;
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        StudentService StudentService = sqlSession.getMapper(StudentService.class);
        result = StudentService.deleteStudentByName(name) > 0 ? true : false;
        sqlSession.close();
        return result;
    }

    /**
     * 根据年龄删除学生
     *
     * @param age 学生的年龄
     * @return 删除成功返回真, 否则返回假
     */
    public boolean deleteStudentByAge(int age) {
        boolean result;
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        StudentService StudentService = sqlSession.getMapper(StudentService.class);
        result = StudentService.deleteStudentByAge(age) > 0 ? true : false;
        sqlSession.close();
        return result;
    }

    /**
     * 根据性别删除学生
     *
     * @param sex 学生的性别
     * @return 删除成功返回真, 否则返回假
     */
    public boolean deleteStudentBySex(String sex) {
        boolean result;
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        StudentService StudentService = sqlSession.getMapper(StudentService.class);
        result = StudentService.deleteStudentBySex(sex) > 0 ? true : false;
        sqlSession.close();
        return result;
    }

    /**
     * 根据提供的学生对象,更新学生信息
     *
     * @param student 学生的对象
     * @return 更新成功返回真,否者返回假
     */
    public boolean updateStudent(Student student) {
        boolean result = false;
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        StudentService StudentService = sqlSession.getMapper(StudentService.class);
        result = StudentService.updateStudent(student) > 0 ? true : false;
        sqlSession.close();
        return result;
    }

}

测试代码

我们使用Junit进行单元测试。创建StudentController对象,通过StudentController对象调用StudentService接口的方法,执行对应的SQL语句。在进行测试的时候,代码会显得非常简洁。

进行修改学生信息的测试。根据数据库中某条信息的数据,创建一个学生对象,更改姓名和年龄信息,调用StudentController对象的updateStudent方法进行修改学生信息。测试结果发现,成功修改信息。注意不能更改Sid信息,就是根据Sid进行更新操作的。

进行添加学生信息的测试。 UUID随机生成一个Sid编号,自拟其他的信息,创建一个Student对象,调用StudentController对象的insertStudent方法添加学生信息。测试结果发现,成功将创建的学生信息添加进入数据库。

进行查找所有学生信息的测试。 查这里测试查找所有学生的信息,通过StudentController对象的selectStudent方法查找所有学生的信息。测试结果发现,后台输出的学生信息,和数据库中存储的学生信息完全一致。可以自行测试关于查找的其他方法。

 进行删除学生信息的测试。通过StudentController对象调用deleteStudent方法删除id编号为1001的学生信息。测试结果发现,成功将数据库中id编号为1001的学生信息删除。

 所有的测试代码。

import com.kid.controller.StudentController;
import com.kid.pojo.Student;
import org.junit.Test;
import java.util.List;
import java.util.UUID;

public class MyTest {

    @Test
    /**
     * 测试查询所有学生信息
     */
    public void testSelectStudentAll() {
        StudentController studentController = new StudentController();
        List<Student> list = null;
        
        //查找前需要注意数据库中是否存在符合查询条件的信息
        list = studentController.selectStudent();//查找所有学生
        list = studentController.selectStudent(1003, "id");
        list = studentController.getStudentAll();
        list = studentController.getStudentById(1004);
        list = studentController.getStudentBySex("男");
        list = studentController.getStudentBySid("4603848f2e8e4769a0d30bf78f3dc562");
        list = studentController.getStudentByName("Kid");
        list=studentController.getStudentByAge(20);
        
        if (list == null) {
            System.out.println("未找到");
        } else {
            System.out.println("输出查询信息");
            for (Student student : list) {
                System.out.println(student);
            }
        }
    }

    @Test
    /**
     * 测试插入学生信息
     */
    public void testInsertStudent() {
        boolean result = false;
        StudentController studentController = new StudentController();
        Student student = new Student(UUID.randomUUID().toString().replace("-", ""), 1020, "黑羽快斗", "1235", 30, "男");

        result = studentController.insertStudent(student);

        if (result) {
            System.out.println("添加成功");
            System.out.println(student);
        } else {
            System.out.println("添加失败");
        }
    }

    @Test
    public void testDeleteStudent() {
        boolean result = false;
        StudentController studentController = new StudentController();

        //删除前需要注意数据库中是否存在符合删除条件的信息
        result = studentController.deleteStudent(1001, "id");
        result = studentController.deleteStudentById(1002);
        result = studentController.deleteStudentBySex("女");
        result = studentController.deleteStudentBySid("fjakslfk349rhrksar4");
        result = studentController.deleteStudentByAge(20);
        result = studentController.deleteStudentByName("Kid");

        if (result) {
            System.out.println("删除成功");
        } else {
            System.out.println("删除失败");
        }
    }

    @Test
    /**
     * 测试更新学生信息
     */
    public void testUpdateStudent() {
        boolean result = false;
        StudentController studentController = new StudentController();
        Student student = new Student("fjakslfk349rhrksar4", 1010, "Kid", "1235", 300, "男");

        System.out.print("原本的数据:");
        System.out.println(studentController.getStudentBySid(student.getSid()));

        result = studentController.updateStudent(student);

        if (result) {
            System.out.println("修改成功");
            System.out.print("修改后的数据:");
            System.out.println(student);
        } else {
            System.out.println("修改失败");
        }
    }


}
  • 1
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值