The first Mybatis program

Posted by baber_abbasi on Fri, 24 Dec 2021 05:33:10 +0100

1. What is MyBatis

  • MyBatis is an excellent persistence layer framework, which supports customized SQL, stored procedures and advanced mapping.

  • MyBatis avoids almost all JDBC code and manually setting parameters and getting result sets.

  • MyBatis can use simple XML or annotations to configure and map native information, and map interfaces and Java POJOs (plain ordinary Java objects) into records in the database.

2. Characteristics

  • Easy to learn: there is no third-party dependency. As long as two jar files + several sql mapping files are configured, it is easy to learn and use
  • Flexibility: mybatis does not impose any impact on the existing design of the application or database. sql is written in xml for unified management and optimization. All requirements for operating the database can be met through sql statements.
  • Decouple sql and program code: by providing DAO layer, separate business logic and data access logic, so as to make the system design clearer, easier to maintain and easier to unit test. The separation of sql and code improves maintainability.
  • Provides a mapping label to support the mapping between the object and the attribute field in the database table
  • Provide object relationship mapping labels to support object relationship construction and maintenance
  • Provide xml tags to support writing dynamic sql

3. Persistence

Data persistence

  • Persistence is the process of transforming program data in persistent state and transient state
  • Memory: loss upon power failure
  • Database (jdbc), io file persistence

Why persistence?

  • Some objects cannot be lost
  • Memory is expensive

4. Persistent layer

DAO layer, servlet layer, controller layer

  • Code block that completes the persistence work
  • Layers are clearly defined

5. Why do you need Mybatis

  • Help us store data in the database
  • convenient
  • Traditional jdbc code is complex, simplified, framework and automatic

6. The first Mybatis program

1. Create database

CREATE DATABASE `mydatabase`;

USE `mydatabase`;

CREATE TABLE `User`(
                        `id` INT(10) NOT NULL AUTO_INCREMENT,
                        `name` VARCHAR(100) NOT NULL,
                        `pwd`  VARCHAR(50) NOT NULL,
                        KEY `id`(`id`)
)ENGINE=INNODB DEFAULT CHARSET=utf8;

INSERT INTO `User`(`id`,`name`,`pwd`) VALUES
 (1,"Zhang San","11"),(2,"Li Si","22"),(3,"Wang Wu","33");

2. Build environment

  • Create a new normal maven project
  • Import maven dependencies
<dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.25</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.7</version>
        </dependency>
		
		<!--It is convenient to write the method of waiting entity class-->
		<dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.22</version>
        </dependency>
</dependencies>

3. Write mybatis XML core configuration file

Here, we write a DB Properties file to store our database configuration

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mydatabase?useSSL=true&useUnicode=true&characterEncoding=utf-8
username=root
password=123456
<?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>

    <properties resource="db.properties"/>


    <!--Environment configuration and connected database are used here MySQL-->
    <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/dao/UserMapper.xml" />
    </mappers>

</configuration>

4. Write the Mybatis tool class to reuse the code

public class MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory;
    static{
                String resource = "Mybatis-config.xml";
        try {
            InputStream inputStream = Resources.getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();
    }

}

5. Writing pojo entity classes

package com.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
//It should be consistent with the attribute field name in the database, otherwise it will require parameters to match, which is very troublesome
public class User {
    private int id;
    private String name;
    private String pwd;
}

6. Write dao interface

package com.dao;

import com.pojo.User;

import java.util.List;

public interface UserMapper {

    //increase
    int add(User user);

    //Delete
    int delete(int id);

    //change
    int update(User user);

    //check
    User query(int id);

    //Check all
    List<User> getAll();
}

7. Write the implementation of UserMapper

In Mybaits, we use xml to write

<?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.dao.UserMapper">

    <!--increase-->
    <insert id="add" parameterType="com.pojo.User">
        insert into mydatabase.user (name,pwd) values(#{name},#{pwd})
    </insert>

    <!--Delete-->
    <delete id="delete" parameterType="com.pojo.User">
        delete
        from mydatabase.user
                 where id = #{id};
    </delete>

    <!--change-->
    <update id="update" parameterType="com.pojo.User">
        update mydatabase.user set name=#{name},pwd=#{pwd} where id = #{id}
    </update>

    <!--check-->
    <select id="query" parameterType="int" resultType="com.pojo.User">
        select * from mydatabase.user where id=#{id}
    </select>

    <!--Check all-->
    <select id="getAll" parameterType="com.pojo.User" resultType="com.pojo.User">
        select *
        from mydatabase.user;
    </select>

</mapper>

8. Writing test classes

import com.dao.UserMapper;
import com.pojo.User;
import com.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;

public class test {

    //Query a
    @Test
    public void test1(){
        SqlSession session = MybatisUtils.getSqlSession();
        UserMapper mapper = session.getMapper(UserMapper.class);
        User user1 = mapper.query(1);
        System.out.println(user1);
    }
    //result:
    //User(id=1, name = Zhang San, pwd=11)

    //Query all
    @Test
    public void test2(){
        SqlSession session = MybatisUtils.getSqlSession();
        UserMapper mapper = session.getMapper(UserMapper.class);
        for (User user : mapper.getAll()) {
            System.out.println(user);
        }
    }
	//result:
    /*User(id=1, name=Zhang San, pwd=11)
	* User(id=2, name=Li Si, pwd=22)
	* User(id=3, name=Wang Wu (pwd=33)
	* User(id=4, name=Zhao Liu, pwd=44)
	*/
    
    //increase
    @Test
    public void test3(){
        SqlSession session = MybatisUtils.getSqlSession();
        UserMapper mapper = session.getMapper(UserMapper.class);
        mapper.add(new User(5,"Xiao Ming","55"));
        for (User user : mapper.getAll()) {
            System.out.println(user);
        }
    }
    //result:
    /*
	*User(id=1, name=Zhang San, pwd=11)
	*User(id=2, name=Li Si, pwd=22)
	*User(id=3, name=Wang Wu (pwd=33)
	*User(id=4, name=Zhao Liu, pwd=44)
	*User(id=5, name=Xiao Ming, pwd=55)
	*/

    //Delete
    @Test
    public void test4(){
        SqlSession session = MybatisUtils.getSqlSession();
        UserMapper mapper = session.getMapper(UserMapper.class);
        mapper.delete(5);
        for (User user : mapper.getAll()) {
            System.out.println(user);
        }
    }
    //result:
    /*
	* User(id=1, name=Zhang San, pwd=11)
	* User(id=2, name=Li Si, pwd=22)
	* User(id=3, name=Wang Wu (pwd=33)
	* User(id=4, name=Zhao Liu, pwd=44)
	*/

    //change
    @Test
    public void test5(){
        SqlSession session = MybatisUtils.getSqlSession();
        UserMapper mapper = session.getMapper(UserMapper.class);
        mapper.update(new User(1, "Zhang San", "11"));
        for (User user : mapper.getAll()) {
            System.out.println(user);
        }
    }
    //result:
    /*
	* User(id=1, name=Zhang San (pwd=111)
	* User(id=2, name=Li Si, pwd=22)
	* User(id=3, name=Wang Wu (pwd=33)
	* User(id=4, name=Zhao Liu, pwd=44)	
	*/
}

9. Possible problems:


This is the file structure of idea. The problem of resource export failure may occur
Here, let's POM XML configuration file

<!--stay build Configuration file in resources,To prevent the failure of resource export-->
    <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>

Topics: Java Database MySQL Mybatis