The Maven project created by IDEA uses the Mybatis framework to simply add, delete, modify and query a single table

Build environment

Build database table

MySQL database is used. Create a new database named task and a new table named student in the task database. Add data to the table as appropriate. The SQL statements for creating tables and adding data are as follows.

SET FOREIGN_KEY_CHECKS=0;
--Create table
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
  `sid` varchar(40) NOT NULL DEFAULT '' COMMENT 'UUID,Unique identification',
  `id` int(10) DEFAULT NULL COMMENT 'Student number',
  `name` varchar(20) DEFAULT NULL COMMENT 'Student name',
  `password` varchar(20) DEFAULT NULL COMMENT 'Student password',
  `age` int(3) unsigned DEFAULT NULL COMMENT 'Student age',
  `sex` varchar(2) DEFAULT NULL COMMENT 'Student gender',
  PRIMARY KEY (`sid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--Add data to table
INSERT INTO `student` VALUES ('9577f4badff2443e9e67bcc63b640341', '1005', 'KID', '12345', '20', 'female');
INSERT INTO `student` VALUES ('9577f4badff2443e9e67bcc63b640342', '1001', 'Zhang San', '1235', '12', 'female');
INSERT INTO `student` VALUES ('c93bbe3c69ed4cbeb07a2a06ccb97612', '1002', 'Li Si', '1235', '30', 'male');
INSERT INTO `student` VALUES ('db7d44de97e1418d95fd73a77b9a9b0c', '1003', 'Wang Wu', '1235', '12', 'female');
INSERT INTO `student` VALUES ('fjakslfk349rhrksar4', '1004', 'Zhao Liu', '1235', '25', 'male');

Create the data table after success.

Create Maven project

Create a Maven project using IDEA.

Create a new project, select Create Maven project, select JDK in your computer, and click next.

  Enter the project name, select the address where the project is stored, and finally click Finish to complete the creation of Maven project.

Introduction of Mybatis framework

Baidu searches for Mybatis and enters the official website of Myabtis. Introduction to mybatis – MyBatis 3https://mybatis.org/mybatis-3/zh/index.html Click the entry on the left, and the dependency code on the right is placed in the project pom.xml file. The dependency code must be placed in < dependencies > < / dependencies >.

You can also get the dependency code of Mybatis in Maven warehouse. The principle is similar to JDBC for obtaining MySQL database. Maven Repository: org.mybatis » mybatis » 3.5.7 (mvnrepository.com)https://mvnrepository.com/artifact/org.mybatis/mybatis/3.5.7 In addition, the JDBC dependency of MySQL database needs to be introduced. You can get the JDBC dependency code of MySQL database in Maven warehouse. Maven Repository: Search/Browse/Explore (mvnrepository.com)https://mvnrepository.com/ Directly search for MySQL in Maven warehouse, select a MySQL type, select the required MySQL version, and paste the dependent code in pom.xml file.

 

To facilitate testing, we also need to add Junit dependencies. The method of adding Junit dependencies is similar to that of adding MySQL dependencies.

Maven Repository: junit » junit » 4.13.2 (mvnrepository.com)https://mvnrepository.com/artifact/junit/junit/4.13.2 When running, the problem of file resource acquisition failure may occur. You can directly copy the following code into the pom.xml configuration file of the project. It is highly recommended to put the following code in each Maven project.

    <!--stay build Medium configuration resources,To prevent resource export failure-->
    <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>

  All dependency and configuration codes used in this project. The code in the pom.xml file.

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

    <!--Add dependent code-->
    <dependencies>

        <!--add to MySQL Database JDBC rely on-->
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.26</version>
        </dependency>

        <!--add to Mybatis Framework dependency-->
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.7</version>
        </dependency>

        <!--add to Junit Unit test dependencies-->
        <!-- https://mvnrepository.com/artifact/junit/junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

    <!--stay build Medium configuration resources,To prevent resource export failure-->
    <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>

After adding dependencies, they may explode red. You need to click the refresh button in the upper right corner to refresh local resources. The problem of red explosion can be solved.

You need to create a mybatis-config.xml file in the outlets package. The file name can be other, but it is best to match the official file name; Copy and paste the official configuration file code into your newly created configuration file. Among them, the path in < mapper > < / mapper > will be changed later.

 

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

You also need to simply configure Mybatis to provide information about connecting to the database.

Here, we use external resources to configure the information of Mybatis connecting to the database.

You need to create a config.properties resource file in the resources folder first.

In the newly created config.properties resource file, add your own database information.

  Introduce external resources in the mybatis-config.xml configuration file. We don't need to change the information in external resources. We can import it directly and use self closing tags.

    <!--Import external profile-->
    <properties resource="config.properties"/>

Write code

Authoring tool classes

Create the package directory as shown in the figure under the java package. The package structure adopts MVC specification, which separates the call from the implementation. controller stores the control layer code, dao package stores the database tool class, pojo package stores the Student instance class, and service package stores the business interface and corresponding configuration files. (it doesn't matter if you don't understand it now. We'll talk about it below)

Create MyBatisUtil.java tool class in dao package to facilitate later use. We need to create a SqlSessionFactoryBuilder object in the MyBatisUtil.java file, then obtain the SqlSessionFactory object through the SqlSessionFactoryBuilder object, and then obtain the SqlSession object through the SqlSessionFactory object. SqlSession provides all the methods required to execute SQL commands in the database. You can execute mapped SQL statements through the SqlSession object.

SqlSessionFactory, as its name implies, is the creation factory of SqlSession. You can use the openSession() method of the SqlSessionFactory object to get the SqlSession object. The opensession () method can pass parameters. When the parameter is true, MyBatis can automatically commit transactions. There is no need to commit transactions when adding, deleting and modifying.

Here, we simply modify the official writing method, create a static SqlSessionFactory object and a static getSqlSession method, and obtain the SqlSession object by calling a static getSqlSession method. In this way, the tool class of MyBatis has been written. Later, you can directly use the getSqlSession() method to obtain the SqlSession object.

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() {
        //To modify the data in the database (addition, deletion and modification), the transaction must be committed, otherwise the data will not be saved to the database
        //Parameter in openSession(true). True automatically commits the transaction
        return sqlSessionFactory.openSession(true);
    }

}

Create instance class

Then create a Student.java class in the pojo package. The properties in this class need to correspond to the properties in the database and need to be created according to the JavaBean specification (private properties, common interfaces). Note that the varchar type in the database maps to the String type in Java.

package com.kid.pojo;

public class Student {
    private String sid;//UUID, unique identification
    private int id;//Student number
    private String name;//Student name
    private String password;//Login password
    private int age;//Age
    private String sex;//Gender

    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 + '\'' +
                '}';
    }
}

Create business interface

When using Mybatis, you need to create a business interface first, and then map the relevant SQL statements in the xml configuration file.

Under the com.kid.service package, first create a StudentService interface to handle the specific business of students. The methods in the interface can be changed according to their own needs.

package com.kid.service;

import com.kid.pojo.Student;

import java.util.List;

public interface StudentService {
    //Increase students
    int insertStudent(Student student);

    //Delete student
    int deleteStudentBySid(String sid);

    int deleteStudentById(int id);

    int deleteStudentByName(String name);

    int deleteStudentByAge(int age);

    int deleteStudentBySex(String sex);

    //Modify student information
    int updateStudent(Student student);

    //Find students
    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);
}

Mapping business interfaces  

Create a StudentServiceImp.xml configuration file under the com.kid.service package, and map the methods in the StudentService interface in the configuration file.

The configuration file needs to be bound to the interface through the namespace in the configuration file, and the namespace needs to be provided with the fully qualified class name of the interface.

Map the lookup method.

  Mapping method of query statement in StudentService interface. You need to use the < Select > < / Select > tag. The attributes in the tag generally use id, parameterType and resultType. id is to bind the tag to the method to be mapped in the interface. The value of id must be the method name in the interface; parameterType is the parameter type required by the method in the interface; resultType is the return value type of the method in the interface. If the return value is a List collection, you need to write the type of the element in the List collection.

Map the methods of adding, deleting and modifying.

The tag attributes added, deleted and modified are very similar. There are two common attributes: id and parameterType: id is to bind the tag to the method to be mapped in the interface, and the value of id must be the method name in the interface; The parameterType attribute can generally be omitted. MyBatis can automatically infer the parameter type of the specific incoming statement.

The mapping code in the StudentServiceImp.xml configuration file.

<?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">

    <!--Add student information-->
    <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>

    <!--Delete student information-->
    <!--according to Sid Delete student-->
    <delete id="deleteStudentBySid" parameterType="String">
        delete
        from task.student
        where sid = #{sid}
    </delete>
    <!--according to id Delete student-->
    <delete id="deleteStudentById" parameterType="int">
        delete
        from task.student
        where id = #{id}
    </delete>
    <!--according to name Delete student-->
    <delete id="deleteStudentByName" parameterType="String">
        delete
        from task.student
        where name = #{name}
    </delete>
    <!--according to age Delete student-->
    <delete id="deleteStudentByAge" parameterType="int">
        delete
        from task.student
        where age = #{age}
    </delete>
    <!--according to sex Delete student-->
    <delete id="deleteStudentBySex" parameterType="String">
        delete
        from task.student
        where sex = #{sex}
    </delete>

    <!--Modify student information-->
    <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>

    <!--Find student information-->
    <!--Find all students-->
    <select id="getStudentAll" resultType="com.kid.pojo.Student">
        select *
        from task.student
    </select>
    <!--according to sid Find students-->
    <select id="getStudentBySid" parameterType="String" resultType="com.kid.pojo.Student">
        select *
        from task.student
        where sid = #{sid}
    </select>
    <!--according to id Find students-->
    <select id="getStudentById" parameterType="int" resultType="com.kid.pojo.Student">
        select *
        from task.student
        where id = #{id}
    </select>
    <!--according to name Find students-->
    <select id="getStudentByName" parameterType="String" resultType="com.kid.pojo.Student">
        select *
        from task.student
        where name = #{name}
    </select>
    <!--according to age Find students-->
    <select id="getStudentByAge" parameterType="int" resultType="com.kid.pojo.Student">
        select *
        from task.student
        where age = #{age}
    </select>
    <!--according to sex Find students-->
    <select id="getStudentBySex" parameterType="String" resultType="com.kid.pojo.Student">
        select *
        from task.student
        where sex = #{sex}
    </select>

</mapper>

We also need to register in mybatis-config.xml to tell MyBatis where to find the SQL statement corresponding to the interface. We registered StudentServiceImp.xml in the mybatis-config.xml file.

In the mybats-config.xml file, insert the following configuration code.

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

Add control layer

The control layer calls the interface of the business layer to realize the specific business. The control layer has little effect on small projects and can be ignored, but for complex projects, the control layer can make the code clearer. Therefore, try to write the code structure according to the specification during practice.

Create the StudentController.java class under the controller package. In the StudentService interface, we write many methods to add, delete, modify and query according to different parameters. In order to facilitate calling, we classify all methods into four categories in the StudentController class, that is, add, delete, modify and find four methods, and distinguish the specific methods called by passing in parameters. The specific process is as follows: first use the MyBatisUtil class to obtain the SqlSession object, then obtain the StudentService object through the SqlSession object, and call its method through the StudentService object. It should be noted that the connection should be closed through the SqlSession object. The specific code is as follows.

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 {

    /**
     * Overload, query all student information without parameters
     *
     * @return Returns a list of information for all students
     */
    public List<Student> selectStudent() {
        return getStudentAll();
    }

    /**
     * Overload, select and call the method to find students according to the parameters
     *
     * @param object Find the value of the parameter required by the student
     * @param str    Find the type of parameters required by students, 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;
    }

    /**
     * Find all student information
     *
     * @return Returns a list of information for all students
     */
    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;
    }

    /**
     * Find student information according to Sid
     *
     * @param sid Student unique ID
     * @return Returns the list of student information that meets the query criteria
     */
    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;
    }

    /**
     * Query student information according to student Id and student number
     *
     * @param id Student number
     * @return Returns the list of student information that meets the query criteria
     */
    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;
    }

    /**
     * Query student information according to student name
     *
     * @param name Student name
     * @return Returns the list of student information that meets the query criteria
     */
    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;
    }

    /**
     * Query student information according to student age
     *
     * @param age Student age
     * @return Returns the list of student information that meets the query criteria
     */
    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;
    }

    /**
     * Query student information according to student gender
     *
     * @param sex Student gender
     * @return Returns the list of student information that meets the query criteria
     */
    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;
    }

    /**
     * Add student information according to the provided Student object
     *
     * @param student Student object
     * @return If the insertion is successful, it returns true, otherwise it returns false
     */
    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;
    }

    /**
     * Select and call the method to delete student information according to the parameters
     *
     * @param object Required parameter value
     * @param str    Delete student basis according to Sid, Id, Name, Sex, Age
     * @return True will be returned if the deletion is successful, otherwise false will be returned
     */
    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;
    }

    /**
     * Delete students according to student 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;
    }

    /**
     * Delete students according to student number
     *
     * @param id Student Id number
     * @return True will be returned if the deletion is successful, otherwise false will be returned
     */
    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;
    }

    /**
     * Delete students by name
     *
     * @param name Student name
     * @return True will be returned if the deletion is successful, otherwise false will be returned
     */
    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;
    }

    /**
     * Delete students by age
     *
     * @param age Student's age
     * @return True will be returned if the deletion is successful, otherwise false will be returned
     */
    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;
    }

    /**
     * Delete students by gender
     *
     * @param sex Gender of students
     * @return True will be returned if the deletion is successful, otherwise false will be returned
     */
    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;
    }

    /**
     * Update student information according to the provided student objects
     *
     * @param student Object of students
     * @return If the update is successful, it returns true. If not, it returns false
     */
    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;
    }

}

Test code

We use Junit for unit testing. Create a StudentController object, call the method of the StudentService interface through the StudentController object, and execute the corresponding SQL statement. When testing, the code will appear very concise.

Conduct a test to modify student information. According to the data of a piece of information in the database, create a student object, change the name and age information, and call the updateStudent method of the StudentController object to modify the student information. The test results show that the information is successfully modified. Note that the Sid information cannot be changed, that is, the update operation is performed according to the Sid.

Conduct the test of adding Student information.   UUID randomly generates a Sid number, draws up other information, creates a Student object, and calls the insertStudent method of the StudentController object to add Student information. The test results show that the created Student information is successfully added to the database.

Conduct a test to find all student information. Check here to find the information of all students, and find the information of all students through the selectStudent method of the StudentController object. The test results show that the student information output from the background is completely consistent with the student information stored in the database. You can test other methods of finding by yourself.

  Test to delete student information. Call the deleteStudent method through the StudentController object to delete the student information with id number 1001. The test results show that the student information with id number 1001 in the database is successfully deleted.

  All test codes.

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
    /**
     * Test and query all student information
     */
    public void testSelectStudentAll() {
        StudentController studentController = new StudentController();
        List<Student> list = null;
        
        //Before searching, you should pay attention to whether there is information matching the query criteria in the database
        list = studentController.selectStudent();//Find all students
        list = studentController.selectStudent(1003, "id");
        list = studentController.getStudentAll();
        list = studentController.getStudentById(1004);
        list = studentController.getStudentBySex("male");
        list = studentController.getStudentBySid("4603848f2e8e4769a0d30bf78f3dc562");
        list = studentController.getStudentByName("Kid");
        list=studentController.getStudentByAge(20);
        
        if (list == null) {
            System.out.println("not found");
        } else {
            System.out.println("Output query information");
            for (Student student : list) {
                System.out.println(student);
            }
        }
    }

    @Test
    /**
     * Test insert student information
     */
    public void testInsertStudent() {
        boolean result = false;
        StudentController studentController = new StudentController();
        Student student = new Student(UUID.randomUUID().toString().replace("-", ""), 1020, "Black feather fast fight", "1235", 30, "male");

        result = studentController.insertStudent(student);

        if (result) {
            System.out.println("Added successfully");
            System.out.println(student);
        } else {
            System.out.println("Add failed");
        }
    }

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

        //Before deleting, you should pay attention to whether there is information in the database that meets the deletion conditions
        result = studentController.deleteStudent(1001, "id");
        result = studentController.deleteStudentById(1002);
        result = studentController.deleteStudentBySex("female");
        result = studentController.deleteStudentBySid("fjakslfk349rhrksar4");
        result = studentController.deleteStudentByAge(20);
        result = studentController.deleteStudentByName("Kid");

        if (result) {
            System.out.println("Delete succeeded");
        } else {
            System.out.println("Deletion failed");
        }
    }

    @Test
    /**
     * Test and update student information
     */
    public void testUpdateStudent() {
        boolean result = false;
        StudentController studentController = new StudentController();
        Student student = new Student("fjakslfk349rhrksar4", 1010, "Kid", "1235", 300, "male");

        System.out.print("Original data:");
        System.out.println(studentController.getStudentBySid(student.getSid()));

        result = studentController.updateStudent(student);

        if (result) {
            System.out.println("Modified successfully");
            System.out.print("Modified data:");
            System.out.println(student);
        } else {
            System.out.println("Modification failed");
        }
    }


}

Keywords: Java MySQL Junit Maven Mybatis

Added by Desdinova on Fri, 17 Sep 2021 17:00:56 +0300