MyBatis learning (detailed steps to build the framework)

Posted by veveu on Mon, 07 Mar 2022 16:28:22 +0100

MyBatis learning

What is MyBatis?

MyBatis is the MyBatis SQL Mapper Framework for Java (sql)

Mapping)

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.

sql mapper: sql mapping

You can map a row of data in the database into a java object.

A row of data can be regarded as a java object. Operating this object is equivalent to operating the data in the table

Data Access Objects (DAOs): data access, adding, deleting, modifying and querying the database.

What features does MyBatis provide?

  1. It provides the ability to create Connection, Statement and ResultSet without developers creating these objects.

  2. It provides the ability to execute sql statements without programmers executing sql themselves.

  3. It provides the ability to cycle sql and convert the result set of sql into java object and list set.

  4. It provides the ability to close resources without closing Connection, Statement and ResultSet.

    Developers provide sql statements - MyBatis handles sql - developers get List sets or Java objects (data in tables).

    Summary: MyBatis is an sql mapping framework, which provides the operation ability of the database. It is an enhanced JDBC. Using MyBatis, however, developers mainly write sql statements. They don't have to care about the creation, destruction and sql execution of Connection, Statement and ResultSet.

Create database (MySQL)

First, create a student information table for later learning and the operated table.

//mysql table creation
CREATE TABLE student2
(
id INT PRIMARY KEY,
NAME VARCHAR(20) NOT NULL,
email VARCHAR(32),
age INT
)

Configure POM xml

Since you need to use the MyBatis framework, you must import the Jar package of MyBatis.

If Maven is used to build the project, it needs to be in POM Add the following dependency code to XML:

<dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis</artifactId>
   <!--  MyBatis Version of  -->
  <version>x.x.x</version>
</dependency>

Since the MyBatis framework operates on the database, the database driver package must be used to connect to the database.

If Maven is used to build the project, it needs to be in POM Add the following dependency code to XML:

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.16</version>
</dependency>

Create Student entity class

Used to store the data obtained from the database:

[the external chain image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-wCN40erd-1618483282776)(C:\Users \ Yang Xingchi squirrel \ appdata \ roaming \ typora \ typora user images \ image-20210415150045251. PNG)]

Create dao

Create a dao interface:

StudentDao interface:

public interface StudentDao {
    //Query all Student data in Student table
    public List<Student> findAllStudent();
}

Create studentdao XML Mapping File

The content in the following configuration file does not need to be memorized. You can know the meaning, which can be found on the MyBatis official website.

Create in the resources resource path:

‚Äč StudentDao.xml file:

<?xml version="1.0" encoding="UTF-8" ?>
<!--
    sql Mapping files: Writing SQL A statement, MyBatis These statements are executed
    1,Specify constraint file
        <!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

        mybatis-3-mapper.dtd : Is the name of the constraint file and the extension is.dtd
    2,Role of constraint file
        Limit and check the labels that appear in the current file. The attributes must comply with MyBatis Requirements.
-->
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--The root label of the current file. Required-->
<!--
    namespace:
        It is called namespace. It is a unique value. You can customize the string.
        But it requires you to use dao The fully qualified name of the interface.
-->
<mapper namespace="com.songshu.dao.StudentDao">
<!--
    A specific label that can be used in the current file to represent a specific operation of the database
    <select>: Represents the query operation and puts the query statement
    <update>: Represents an update operation, including an update statement
    <insert>: Indicates the insertion operation, and puts the insertion statement
    <delete>: Indicates the deletion operation, and puts the deletion statement
    id: To execute sql Unique identification of the statement, MyBatis Will use this id Value to find the to execute sql sentence
        It can be customized, but you are required to use the method name in the interface
    resultType: Indicates the result type, yes sql Obtained after statement execution ResultSet Yes, I got it java Type of object
-->
    <select id="findAllStudent" resultType="com.songshu.domain.Student">
        select id,name,email,age from student3 order by id
    </select>
</mapper>

Create MyBatis master profile

Create in the resources resource path:
Create mybatis XML file:

<?xml version="1.0" encoding="UTF-8" ?>
<!--
    MyBatis Main configuration file: mainly defines the configuration information of the database, sql Location of mapping file
-->
<!--
    1,Constraint file
        dtd/mybatis-3-config.dtd : The name of the constraint file
-->
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<!--    2,configuration Root label -->
<configuration>
    <!--Environment configuration: database connection information
        default: Must be with someone environment of id equally
        tell MyBatis The connection information of which database to use, that is, which database to access.
    -->
    <environments default="mydev">
        <!--
            environment: A database information configuration, environment
            id: A unique value, custom, representing the name of the environment
            There can be multiple environments. Such as different databases.
        -->
        <environment id="mydev">
            <!--
                transactionManager: MyBatis Types of things
                    type: JDBC(express JDBC Medium Connection Object commit and rollback Do transaction processing
            -->
            <transactionManager type="JDBC"/>
            <!--
                dataSource: Represents a data source and connects to a database
                type: Indicates the type of data source, POOLED Indicates that the database connection pool is used
            -->
            <dataSource type="POOLED">
                <!--driver,url,username,password It is fixed and cannot be customized-->
                <!--Driver class name of the database-->
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <!--Database url character string-->
                <!--Because of my mysql The dependent version is high, so it should be added serverTimezone=GMT%2B8-->
                <property name="url" value="jdbc:mysql://localhost:3306/school?serverTimezone=GMT%2B8"/>
                <!--User name of the database-->
                <property name="username" value="root"/>
                <!--Password for database-->
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    <!--sql mapper(sql Location of mapping file)-->
    <mappers>
        <!--One mapper Label specifies the path of a file
            Path information starting from the classpath. target/classes(Class path), which can be seen after compilation
        -->
        <mapper resource="studentDao.xml"/>
    </mappers>
</configuration>

test

Only 2-3 places in the test code need to be modified and marked as important (after the framework is built)

public class test {
    @Test
    public void test1() throws IOException {
        //Access MyBatis to read student data
        //1. Define the name of the MyBatis main configuration file, starting from the root of the classpath (target/classes)
        String config = "mybatis.xml";
        //2. Read the file represented by this config
        InputStream is = Resources.getResourceAsStream(config);
        //3. Create SqlSessionFactoryBuilder object
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        //4. Create SqlSessionFactory object
        SqlSessionFactory factory = builder.build(is);
        //5. [important] get the SqlSession object and get the SqlSession from the SqlSessionFactory
        SqlSession sqlSession = factory.openSession();
        //6. [important] specify the identification of the sql statement to be executed. id of namespace + "." + tag in sql mapping file
        String sqlId = "com.songshu.dao.StudentDao.findAllStudent";
        //7. Execute the sql statement and find the sql statement through sqlId
        List<Student> students = sqlSession.selectList(sqlId);
        //8. Output results
        students.forEach(stu -> System.out.println(stu));
        //9. Close the SqlSession object
        sqlSession.close();
    }
}

The framework is basically completed. If you need more in-depth study, you can go to the official website.


If there is any error, please point it out, thank you!

Topics: Java JDBC Mybatis