Use Mybatis to write a simple addition, deletion, modification and query

First of all, we should think of a good idea: build an environment -- > Import mybatis -- > write code -- > test

This simple project uses the environment: JDK1.8,IDEA 2019,MySQL, maven 3.5.0

1. Build environment

1.1 build a simple database

Create a database named mybatis and use it. The code is as follows:

CREATE DATABASE `mybatis`;

use `mybatis`;

  Create a table named user with the following code:

CREATE TABLE `user`(
    `id` INT(20) NOT NULL PRIMARY KEY,
    `name` VARCHAR(30) DEFAULT NULL,
    `pwd` VARCHAR(30) DEFAULT NULL
)ENGINE-INNODB DEFAULT CHARSET=utf-8;

Insert some data into the user table. The code is as follows:

INSERT INTO `user`(`id`,`name`,`pwd`) VALUES
(1001,'Zhang San','12345'),
(1002,'Li Si','13245'),
(1003,'Wang Wu','11234')

  1.2 create a new project

  Create a normal Maven project

 

Be sure to take good care of your Maven environment to avoid mistakes.

According to my learning habits, I generally like to delete the src file and create a sub module under the parent project, which can facilitate the management of multiple projects without multiple configurations. The operations are as follows:

 

Such a project is ready. Of course, you should choose the most suitable way to build your favorite project.

I put the whole project structure in advance, which is roughly as follows:

  2. Import Mybatis

2.1 import Mybatis dependency

Import the Mybatis dependency in POM.XML under the parent project. The code is as follows

<?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>
    <!-- Parent project-->
    <groupId>com.cyf</groupId>
    <artifactId>Mybatis-Study</artifactId>
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>
    <!--Subproject -->
    <modules>
        <module>mybaits-01</module>
    </modules>

    <!--Import dependency-->
    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>
    <!--    stay build Medium configuration resources , To prevent the failure of resource export-->
    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>
    </build>
</project>

  Create a db.properties under SRC > main > resources in the sub module mybatis-01 and write the parameters. The code is as follows:

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?userSSL=true&;useUnicode=true&;characterEncoding=UTF-8
username=root
password=root

Create a mybatis-config.xml under SRC > main > resources in the sub module mybatis-01 and write the Mybatis core configuration file. The code is as follows:

<?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 Core profile-->
<configuration>
    <properties resource="db.properties">
        <property name="username" value="username"/>
        <property name="password" value="password"/>
    </properties>
    <typeAliases>
        <typeAlias type="com.cyf.pojo.User" alias="User"/>
    </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="com/cyf/mapper/UserMapper.xml"/>
    </mappers>
</configuration>

In the sub module, SRC > main > java under mybatis-01 creates a package of com.cyf.util, creates a MybatisUtils in it, and writes a mybatis tool class. The code is as follows:

package com.cyf.util;

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 MybatisUtils {

    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(){
        
        return sqlSessionFactory.openSession();
    }
}

3. Write code

You need to write entity classes, Mapper interfaces, and Mapper configuration files.

Entity class: create a package of com.cyf.pojo in SRC > main > java under mybatis-01 in the sub module, and write a User class. The code is as follows:

package com.cyf.pojo;

public class User {
    private int id;
    private String name;
    private String psw;

    public User() {
    }

    public User(int id, String name, String psw) {
        this.id = id;
        this.name = name;
        this.psw = psw;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", psw='" + psw + '\'' +
                '}';
    }
    
    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 getPsw() {
        return psw;
    }

    public void setPsw(String psw) {
        this.psw = psw;
    }
}

Mapper interface: create a com.cyf.mapper package in SRC > main > java under mybatis-01 in the sub module, and write a UserMapper interface. The code is as follows:

package com.cyf.mapper;

import com.cyf.pojo.User;

import java.util.List;

public interface UserMapper {
    List<User> getUserList();

    User getUserById(int id);

    int addUser(User user);

    int updateUser(User user);

    User deleteUser(int id);
}

Mapper configuration file: create a com.cyf.mapper package in SRC > main > java under mybatis-01 in the sub module, and write a UserMapper.xml file. The code is as follows:

<?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.cyf.mapper.UserMapper">
    <select id="getUserList" resultType="User">
        select * from mybatis.user
    </select>
    
    <select id="getUserById" resultType="User" parameterType="int">
        select * from mybatis.user where id = #{id}
    </select>

    <select id="addUser" parameterType="User">
        insert into mybatis.user (id,name,psw) values (#{id},#{name},#{psw});
    </select>

    <select id="updateUser" parameterType="User">
        update mybatis.user  set name=#{name},psw=#{psw} where id = #{id};
    </select>

    <select id="deleteUser" resultType="User" parameterType="int">
        delete from mybatis.user where id=#{id}
    </select>

</mapper>

4. Test

Junit test class: create a com.cyf.mapper package in SRC > test > java under mybatis-01 in the sub module, and write a UserMapperTest test class. The code is as follows:

package com.cyf.mapper;

import com.cyf.pojo.User;
import com.cyf.util.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;

public class UserMapperTest {
    @Test//List all data
    public void getUserList(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        List<User> userList = userMapper.getUserList();

        for (User user : userList){
            System.out.println(user);
        }
        sqlSession.close();
    }
    @Test //Query by id
    public void getUserById(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        User user = userMapper.getUserById(3);
        System.out.println(user);
        sqlSession.close();
    }
    @Test  //Add data
    public void addUser(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        int res = userMapper.addUser(new User(4,"Zhao Liu","1234567"));
        if (res>0) {
            System.out.println("Submitted successfully");
        }
        sqlSession.commit();
        sqlSession.close();
    }
    @Test  //Modify data
    public void updateUser(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        userMapper.updateUser(new User(3,"Jiro ","12345"));
        sqlSession.commit();
        sqlSession.close();
    }

    @Test    //Delete data
    public void deleteUser(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        userMapper.deleteUser(4);
        sqlSession.commit();
        sqlSession.close();
    }
}

In this way, write a simple CRUD (add, delete, modify and check) using Mybatis!

I also share my learning achievements as a beginner. Please forgive me if there is anything bad!

Tags: Java Database Mybatis SQL

Posted on Tue, 21 Sep 2021 02:20:57 -0400 by dixondwayne