MyBatis Learning Summary (I) - MyBatis Quick Start

github synchronous update
Blog Synchronization Updates
Synchronized Updating of Brief Books
Reference address
Project address: Portal

  • 1. Create table structure
        create database mybatis;
        use mybatis;
        CREATE TABLE users(id INT PRIMARY KEY AUTO_INCREMENT, NAME VARCHAR(20), age INT);
        INSERT INTO users(NAME, age) VALUES('wolf', 27);
        INSERT INTO users(NAME, age) VALUES('tiger', 27);
  • 2. Environmental Configuration

First right-click on the project, click Open Model Set, then click on the + number on the right, select jar, and add the lib directory of the project

Add Mybatis configuration file conf.xml and create a conf.xml file in the src directory, 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>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC" />
            <!-- Configure database connection information -->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver" />
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis" />
                <property name="username" value="root" />
                <property name="password" value="123456" />
            </dataSource>
        </environment>
    </environments>

</configuration>
  • Add the entity class corresponding to the User table
package com.shi.mybatis;

/**
 * @author AfinalStone
 * users Entity classes corresponding to tables
 */
public class User {

    //Attributes of entity classes and field names of tables correspond one by one
    private int id;
    private String name;
    private int age;

    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 int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User [id=" + id + ", name=" + name + ", age=" + age + "]";
    }
}
  • Define the sql mapping file userMapper.xml for the operation users table

Create a com.shi.mapping package for storing sql mapping files, and create a userMapper.xml file in the package, as shown in the following figure:

<?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">
<! - Specify a unique namespace for this mapper, and the value of namespace is customarily set to the package name + sql mapping file name, so that the value of namespace is guaranteed to be unique.
For example, namespace="com.shi.mapping.userMapper" is com. shi. mapping (package name) +userMapper(userMapper.xml file removes suffix)
 -->
<mapper namespace="com.shi.mapping.userMapper">
    <! - Write the query SQL statement in the select tag, set the id attribute of the select tag to getUser, and the id attribute value must be unique and cannot be repeated.
    Use the parameterType attribute to specify the type of parameter used in the query, and the resultType attribute to specify the type of result set returned by the query
    resultType="com.shi.mapping.User" means that the query result is returned as an object encapsulated in a User class.
    The User class is the entity class corresponding to the users table.
    -->
    <!--
        Get a user object from an id query
     -->
    <select id="getUser" parameterType="int"
            resultType="com.shi.mybatis.User">
        select * from users where id=#{id}
    </select>
</mapper>
  • Register userMapper.xml file in conf.xml 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>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC" />
            <!-- Configure database connection information -->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver" />
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis" />
                <property name="username" value="root" />
                <property name="password" value="123456" />
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <!-- register userMapper.xml Documents,
        userMapper.xml Be located com.shi.mapping This package, so resource finish writing sth. com/shi/mapping/userMapper.xml-->
        <mapper resource="com/shi/mapping/userMapper.xml"/>
    </mappers>

</configuration>
  • Writing main program code
package com.shi.mybatis;

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


    public static void main(String[] args) throws IOException {
        //mybatis configuration file
        String resource = "conf.xml";
        //Loading mybatis configuration files using class loaders (it also loads associated mapping files)
        InputStream is = Main.class.getClassLoader().getResourceAsStream(resource);
        //Construction of the factory of sqlSession
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
        //Load the configuration file of mybatis using the Resources class provided by MyBatis (it also loads the associated mapping file)
        //Reader reader = Resources.getResourceAsReader(resource);
        //Construction of the factory of sqlSession
        //SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
        //Create sqlSession that executes sql in the mapping file
        SqlSession session = sessionFactory.openSession();
        /**
         * Mapping sql's identifier string,
         * com.shi.mapping.userMapper Is the value of the namespace attribute of the mapper tag in the userMapper.xml file.
         * getUser Is the id attribute value of the select tag, through the id attribute value of the select tag, you can find the SQL to be executed.
         */
        String statement = "com.shi.mapping.userMapper.getUser";//Identity String Mapping sql
        //Query execution returns sql for a unique user object
        User user = session.selectOne(statement, 1);
        System.out.println(user);
    }
}
  • Finally, take a look at the overall structure of the project and the output results, and here we have successfully used the MyBatis framework in the project:

Project address: Portal

Keywords: Mybatis xml SQL Attribute

Added by phigga on Wed, 19 Jun 2019 20:58:53 +0300