First day of Mybatis

First day of Mybatis

1.1 what is Mybatis

MyBatis is an excellent persistence layer framework, which supports custom SQL, stored procedures and advanced mapping. MyBatis eliminates almost all JDBC code and the work of setting parameters and obtaining result sets. MyBatis can configure and map primitive types, interfaces and Java POJO s (Plain Old Java Objects) to records in the database through simple XML or annotations.

1.2 best learning Mybatis website

MyBatis official website

1.3 why do we need Mybatis

  • Mybatis is to help programs store data in the database and get data from the database

  • The traditional jdbc operation has many repeated code blocks, such as the encapsulation of data extraction, the establishment of database connection, etc. through the framework, the repeated code can be reduced and the development efficiency can be improved

  • MyBatis is a semi-automatic ORM framework (object relationship mapping) - > object relationship mapping

  • The advantages of MyBatis are simple and easy to learn: it is small and simple in itself.

    1. There is no third-party dependency. The simplest installation is as long as two jar files + several sql mapping files are configured. It is easy to learn and use. Through documents and source code, you can fully master its design idea and implementation
    2. 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.
    3. 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.
    4. Provide xml tags to support writing dynamic sql.
    5. wait

2. My first Mybatis program

Thought process: build environment - > Import Mybatis - > write code - > test

2.1 building database

CREATE DATABASE `mybatis`;
USE `mybatis`

CREATE TABLE `user`(
`id` INT(20) NOT NULL,
`name` VARCHAR(30) DEFAULT NULL,
`pwd` VARCHAR(30) DEFAULT NULL,
PRIMARY KEY (`id`)

)ENGINE=INNODB DEFAULT CHARSET=utf8;

INSERT INTO `user` (`id`,`name`,`pwd`) VALUES (1,'Zhang Yifei','11111'),(2,'Feige','23232'),(3,'Baoqing','123123')

2.2 import MyBatis related jar packages

Import mysql driver, mybatis and junit packages

<dependencies>
    <!--mysql drive-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
    <!--mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>
    <!--junit-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

2.3 code demonstration

1. Write MyBatis core configuration file

<?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>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="123123"/>
            </dataSource>
        </environment>
    </environments>
<!--every last Mapper.XML All need to be in Mybatis Register in core profile-->
    <mappers>
        <mapper resource="com/zhang/dao/UserMapper.xml"/>
    </mappers>
</configuration>

Key modification

<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="123123"/>

<!--every last Mapper.XML All need to be in Mybatis Register in core profile-->
    <mappers>
        <mapper resource="com/zhang/dao/UserMapper.xml"/>
    </mappers>

2. Write mybatis tool class

package com.zhang.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;

/**
 * @author feige
 * @create 2021-09-17 16:34
 */

//sqlSessionFactory--->sqlSession
public class MybatisUtils {

    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            //Step 1 of using Mybatis: get sqlSessionFactory object
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //Now that we have SqlSessionFactory, as the name suggests, we can get an instance of SqlSession from it.
    //SqlSession provides all the methods required to execute SQL commands in the database
    public static SqlSession getSqlSession(){
        SqlSession sqlSession = sqlSessionFactory.openSession();
        return sqlSession;
        //return sqlSessionFactory.openSession()
    }
}

3. Write entity class

package com.zhang.pojo;

/**
 * @author feige
 * @create 2021-09-17 16:45
 */
public class User {
    private int id;
    private String name;
    private String pwd;

    public User() {
    }

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

    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 getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

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

4. Write Mapper interface class

package com.zhang.dao;

import com.zhang.pojo.User;

import java.util.List;

/**
 * @author feige
 * @create 2021-09-17 16:47
 */
public interface UseMapper {
    
    //Query all users
    List<User> getUserList();
    
}

5.namespace is very important

<?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=Bind a corresponding Dao/Mapper Interface-->
<mapper namespace="com.zhang.dao.UseMapper">
    <!--select Query statement-->
    <select id="getUserList" resultType="com.zhang.pojo.User">
        select * from mybatis.user;   //sql statement   
    </select>
 </mapper>

6. Write test class

public class UserDaoTest {
    @Test
    public void test(){
        //Step 1: get SqlSession object
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        //Method 1: execute SQL
        UseMapper mapper = sqlSession.getMapper(UseMapper.class);
        List<User> userList = mapper.getUserList();
        for(User user:userList){
            System.out.println(user);
        }
        //Close SqlSession
        sqlSession.close();
    }
}

7. Operation test

2.4 problem description

Problems encountered

Maven static resource filtering problem

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

3CRUD operation

3.1 select

  • The select tag is one of the most commonly used tags in mybatis
  • The select statement has many properties, and each SQL statement can be configured in detail
  • The unique identifier in the ID namespace. The method name in the interface corresponds one-to-one with the SQL statement ID in the mapping file. parameterType is the parameter type of the incoming SQL statement.
  • Resulttype the return value type of the SQL statement. [complete class name or alias]

Query user according to user id

  1. Add corresponding method in UserMapper

    public interface UserMapper {
    //Query all users
    List<User> selectUser();
    //Query user by id
    User selectUserById(int id);
    }
    
  2. Add a Select statement in UserMapper.xml

    <select id="getUserById" parameterType="int" resultType="com.zhang.pojo.User">
         select * from mybatis.user where id=#{id};
    </select>
    
  3. Test in test class

    @Test
        public void getUserById(){
            SqlSession sqlSession = MybatisUtils.getSqlSession();
            UseMapper mapper = sqlSession.getMapper(UseMapper.class);
    
            User userById = mapper.getUserById(1);
            System.out.println(userById);
    
    
            sqlSession.close();
        }
    

Summary
1. All addition, deletion and modification operations need to commit transactions
2. Try to write @ Param parameter for all common parameters of the interface, especially when there are multiple parameters, it must be written!
3. Sometimes, according to business requirements, you can consider using map to pass parameters!
4. In order to standardize the operation, we try to write the Parameter parameter and resultType in the SQL configuration file!

Tags: Java Database SQL

Posted on Sat, 18 Sep 2021 10:04:04 -0400 by dutchboy