The first Mybatis program for basic Mybatis learning

Preface:

Hello, ladies and gentlemen, I'm running like a snail rz. Of course you can call me Snail Jun. I'm a beginner who has studied Java for more than half a year. At the same time, I have a great dream that I will become an excellent Java architect one day.
This Mybatis Basic Learning series is used to record the whole process of my learning the fundamentals of the Mybatis framework (this series was written with reference to the latest Mybatis tutorial from Station B. Since it was sorted out before, but it was not published at that time, there may be errors in some places, I hope you can correct them in time!)
After that, I will update the series at a faster rate each day, and those who haven't yet learned the Mybatis3 framework can refer to my blog to learn about it. Of course, the little buddy who has studied can also review the basics with me by the way.
Finally, I hope I can make progress with you! Come on! Boys!

Say nothing more. Let's start today's learning. Today we come to the first stop of basic Mybatis learning: the first Mybatis program!

3. First Mybatis program

Idea: Set up environment --> Import Mybatis --> Write code --> Test

3.1 Build environment

Create Database `MyBatis`;

Use `MyBatis`;

Create table `User`(
	`id` int(10) not null primary key,
    `name` varchar(30) default null,
    `pwd` varchar(30) default null
)engine=InnoDB default charset=utf8;

Insert into `User`(`id`,`name`,`pwd`) values
(1,'Jay Chou','zjl123456'),
(2,'Fang Wen Shan','fws123456'),
(3,'Huang Junlang','hjl123456')

3.2 New Project

1. Create a new normal maven project

2. Delete src directory

3. Import maven dependencies

<?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.kuang</groupId>
    <artifactId>Mybatis-Study</artifactId>
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>
    <modules>
        <module>mybatis-01</module>
    </modules>
    <!-- Import Dependency -->
    <dependencies>
        <!-- mysql Database Driver -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <!-- mybatis -->
        <!-- https://mvnrepository.com/artifact/org.mybatis/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.12</version>
        </dependency>
    </dependencies>
    <!-- stay build Configuration in resources,To prevent our resource export from failing -->
    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>
</project>

3.3 Create a module

3.3.1 IDEA Connection to MySQL Database Steps

1. Add a database

2. Test Connection

3. Select the target database

4. Connection complete

5. Solution for database connection failure

Encountered during test connection

Solution: Set time zone for MySQL database

1. Connect mysql
mysql  -u root -p

2. View the system default time zone
show variables like'%time_zone';

3. Set a new time zone
set global time_zone = '+8:00'; 
4. View the modified time zone

Note that you need to exit the command window and reenter to see the modified time zone

show variables like'%time_zone';

3.3.2 Writing the core configuration file for mybatis

<?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">
<!-- Core Profile -->
<configuration>
    
    <!-- Environmental Science -->
    <environments default="development">
        <environment id="development">
            <!-- transaction management -->
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>

    <!-- Every last Mapper.xml Need to be done again Mybatis Register in Core Profile -->
    <mappers>
        <mapper resource="com/kuang/dao/UserMapper.xml"/>
    </mappers>
    
</configuration>

3.3.3 Writing the mybatis tool class

// sqlSessionFactory --> sqlSession
public class MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory;
    // Static Method Body
    static {
        try {
            // Step 1 using mybatis: Get the SqlSessionFactory object
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
   /**
    * Now that we have the SqlSessionFactory, as the name implies, we can get an instance of SqlSession from it
    * SqlSession Provides all the methods required to execute SQL commands in a database
    */
   public static SqlSession getSqlSession() {
//       SqlSession sqlSession = sqlSessionFactory.openSession();
//       return sqlSession;
       // Code optimization for the same purpose as the above two sentences
       return sqlSessionFactory.openSession();
   }
}

3.4 Writing code

3.4.1 User Entity Class

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

3.4.2 Mapper interface

public interface UserMapper {
    
    // Return a User to get all users
   List<User> getUserList();
    
}

3.4.3 Mapper Profile

1. UserDao implementation class

  • UserDao implementation class used previously
public class UserDaoImpl implements UserDao {
    
    public List<User> getUserList() {
        // Execute SQL to connect to database
        String sql = "select * from mybatis.user";
        // ResultSet
        return null;
    }
    
}

2. Mapper Profile

  • Change from UserDaoImpl to a Mapper configuration file
<?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.kuang.dao.UserMapper">
    
    <!--select Query Statement:
        There select A label is actually equivalent to Dao Implement method overrides within classes to execute SQL,Connect to database
        resultType: Equivalent to the result, returning one; resultMap: Equivalent to a set, returning multiple -->
    <!-- select Of id Property, the same as the method name defined in the interface -->
    <select id="getUserList" resultType="com.kuang.pojo.User">
        select * from mybatis.user
    </select>
    
</mapper>

3.5 Code Test

3.5.1 MapperRegistry

1. Problems encountered

Type interface com.kuang.dao.UserDao is not known to the MapperRegistry.

2. Problem Analysis

What is MapperRegistry?

Register mappers in core profile

  <!-- Every last Mapper.xml Need to be done again Mybatis Register in Core Profile -->
    <mappers>
        <mapper resource="com/kuang/dao/UserMapper.xml"/>
    </mappers>

3.5.2 junit Test

1. Use the getMapper() method

  • Use the getMapper method to get interface objects without regard to cast
public class UserDaoTest {
    
    @Test
    public void test(){
        
        // Step 1: Get the SqlSession object
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        
         /**
         * It is recommended that you use a try-catch-finally statement to catch exceptions.
         * And write the closing sqlSession in the final statement block to ensure the closing of each execution
         */
        try { 
            // Get UserMapper classes from getMapper (using reflection)
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            // Execute the method in userDao and return the User object in the List set
            List<User> userList = userMapper.getUserList();
            // Traversing the array: You can use the userList.for shortcut key to make a for loop
            for (User user : userList) {
                System.out.println(user);
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally {
        // Close sqlSession
        sqlSession.close();
        }
        
    }
}

2. Use the selectList() method

  • Use the return value of a particular method to return, not recommended
public class UserDaoTest {
    
    @Test
    public void test(){
        // Step 1: Get the SqlSession object
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        try { 
                List<User> userList= sqlSession.selectList("com.kuang.dao.UserDao.getUserList");
        //        List<User> userList1= sqlSession.selectOne ("com.kuang.dao.UserDao.getUserList");// A return value
        //        List<User> userList2= sqlSession.selectMap ("com.kuang.dao.UserDao.getUserList"); // Multiple Return Values
           // Use a for loop to iterate through a collection of user lists
            for (User user : userList) {
                System.out.println(user);
            }
        }catch(Exception e){
            e.printStackTrace();
        }finally {
        // Close sqlSession
        sqlSession.close();
        }
    }
    
}

3.6 Problems encountered

1. Profile not registered

    <!-- Every last Mapper.xml Need to be done again Mybatis Register in Core Profile -->
    <mappers>
        <mapper resource="com/kuang/dao/UserMapper.xml"/>
    </mappers>

2. Binding interface error

<!-- namespace=Bind a corresponding Dao/Mapper Interface -->
<mapper namespace="com.kuang.dao.UserDao">

3. Method name is incorrect

<!--select Of id Property, the same as the method name defined in the interface-->
    <select id="getUserList" resultType="com.kuang.pojo.User">
        select * from mybatis.user
    </select>

4. Incorrect return type

<!-- resultType: Equivalent to the result, returning one; resultMap: Equivalent to a set, returning multiple -->
    <select id="getUserList" resultType="com.kuang.pojo.User">
        select * from mybatis.user
    </select>

5.Maven Exports Resource Resources

<!-- stay build Configuration in resources,To prevent our resource export from failing -->
    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
               <!-- Need to put filtering Change to false -->
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>

3.7 Knowledge Expansion

1.SqlSessionFactoryBuilder

  • SqlSessionFactoryBuilder–>SqlSessionFactory–>SqlSession

2.SqlSession

Okay, that's the end of today's learning about the first Mybatis program. Welcome your friends to actively study and discuss. If you like, you can give Jun Snail some attention. By the way, I'll see you next time. Bye!

Reference video link: https://www.bilibili.com/video/BV1NE411Q7Nx?spm_id_from=333.999.0.0([Crazy Java]) Mybatis latest complete tutorial IDEA version is easy to understand)

Keywords: Java MySQL Mybatis IDEA

Added by kra on Mon, 18 Oct 2021 19:23:45 +0300