MyBatis - MyBatis realizes adding, deleting, modifying and checking

MyBatis - MyBatis realizes adding, deleting, modifying and checking

1. Create a database


2. Create the following structure for the Maven project, remember to mark the java and resources directories as resource directories

3. Guide, configure 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>com.muan</groupId>
    <artifactId>MyBatis Practice</artifactId>
    <version>1.0-SNAPSHOT</version>


    <dependencies>
        <!--unit testing-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
        </dependency>

        <!--mybatis Package-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.1</version>
        </dependency>

        <!--Driver Pack for Connecting to Database-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/log4j/log4j -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
    </dependencies>

    <build>
        <!--hope maven When exporting a project,Ability to export our configuration and resources-->
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>

</project>

4. Write the entity class User under the pojo package

package com.muan.pojo;

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

    public User() {
    }

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

    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;
    }

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

5. Writing dao Layer Interface

package com.muan.dao;

import com.muan.pojo.User;

import java.util.List;

public interface UserMapper {
    //Get all users
    List<User> getAllUser();

    //Getting users through id
    User getUserById(int id);

    //Add a user
    int addUser(User user);

    //Delete users by id
    int deleteUserById(int id);

    //Modify Users
    int modify(User user);
}

6. Write corresponding xml files and SQL

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

<! - namespace: Map the interface we've written, and remember that you must never forget to write - >.
<mapper namespace="com.muhan.dao.UserMapper">

    <!-1. Acquire all users - >.
    <!--
    Write result set mappings:
    Because the password of pojo we wrote does not correspond to the pwd name in the database.
    So you need to use resultMap instead of resultType to map results and deal with different names.
    -->
    <resultMap id="User" type="com.muhan.pojo.User">
        <id property="id" column="id"/>
        <result property="name" column="name"/>
        <result property="password" column="pwd"/>
    </resultMap>
    <! - id: method name in the interface; resultMap: ID corresponding to the result set mapping above
    <select id="getAllUser" resultMap="User">
        select * from user
    </select>


    <!-2. Obtaining users through id - >
    <! - In this case #{id} represents the value from outside - > The value of {id} in the form of {id} in the form of {id} in the form of {id} in the form of {id}
    <select id="getUserById" resultType="com.muhan.pojo.User">
        select * from user where id=#{id}
    </select>


    <!-3. Add a user - >.
    <! - Special note: All but select uses parameterType: the type of parameter passed in - >.
    <insert id="addUser" parameterType="com.muhan.pojo.User">
        insert into user(id,name,pwd) values (#{id},#{name},#{password})
    </insert>


    <!-4. Delete users through id - >
    <delete id="deleteUserById" parameterType="int">
        delete from user where id=#{id}
    </delete>
    
    <! - 5. Modify Users - > Modify Users
    <update id="modify" parameterType="com.muhan.pojo.User">
        update user set name=#{name},pwd=#{password} where id=#{id}
    </update>   
</mapper>

7. Write JDBC configuration file database.properties

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

8. Configure mybatis-config.xml

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

    <!--Quote JDBC configuration file-->
    <properties resource="database.properties"/>

    <!--Configuration environment-->
    <environments default="myenvironment">
        <environment id="myenvironment">
            <!--Configuration transaction management-->
            <transactionManager type="JDBC"></transactionManager>
            <!--Configuring data sources-->
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
                <property name="url" value="${url}"/>
            </dataSource>
        </environment>
    </environments>


    <!--Association mapping file userMapper.xml-->
    <mappers>
        <mapper resource="com/muhan/dao/userMapper.xml"/>
    </mappers>
</configuration>

9. Write mybatis tool class

package com.muhan.utils;

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 {
    //Class variables do not need to set default values;
    private static SqlSession sqlSession;

    static {

        //In maven, all resource files are usually placed in the resources directory, and we can get them directly.
        try {
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            sqlSession= sqlSessionFactory.openSession();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    //Method of setting up SqlSessionFactory public
    public static SqlSession getSqlSession(){
        return sqlSession;
    }
}

10. Testing: Writing test classes in the Test directory

  • Get all users
    @Test
    public void getAllUserTest(){
        //Getting sqlSessionFactory objects through tool classes
        SqlSession sqlSession = MyBatisUtils.getSqlSession();
        //Get the mapper queue, and the parameters are passed in the class object of the interface class
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        //Calling methods through mapper objects
        List<User> allUser = mapper.getAllUser();
        for (User user : allUser) {
            System.out.println(user);
        }
    }

Effect demonstration:

  • Getting users through id
 
    @Test
    public void getUserById(){
        SqlSession sqlSession = MyBatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User userById = mapper.getUserById(1);
        System.out.println(userById);
    }

Effect demonstration:

  • Adding users: Attention to transaction submission and closure
    //Adding users
    @Test
    public void addUser(){
        SqlSession sqlSession = MyBatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = new User(4, "Cutie", "123456");
        mapper.addUser(user);
        sqlSession.commit();
        sqlSession.close();
    }

Effect demonstration:

  • Delete users through id: pay attention to transaction submission and closure
    @Test
    public void deleteUserById(){
        SqlSession sqlSession = MyBatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        mapper.deleteUserById(4);
        sqlSession.commit();
        sqlSession.close();
    }

Effect demonstration:

  • Modifying Users: Pay Attention to Transaction Submission and Closing Transactions
    @Test
    public void modify(){
        SqlSession sqlSession = MyBatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = new User(4, "Cutie", "5678");
        mapper.modify(user);
        sqlSession.commit();
        sqlSession.close();
    }

Effect demonstration:

Keywords: Mybatis xml Maven Apache

Added by lampquest on Sun, 04 Aug 2019 11:21:18 +0300