MyBatis usage and case

1. Introduction to MyBatis

MyBatis is an excellent persistence layer framework for simplifying JDBC development. Official documentation:  mybatis – MyBatis 3 | Introduction

JavaEE three-tier architecture: presentation layer, business layer, persistence layer. The persistence layer is responsible for the layer of code that saves data to the database.

A framework is a semi-finished software. It is a set of reusable, general-purpose, software-based code models. Building software on the basis of the framework is more efficient, standardized, general-purpose, and scalable.

The JDBC encoding process is very cumbersome and hard-coded, which is also very inconvenient for later maintenance. Every time you use it, you need to register the driver, obtain the Connection connection, accept the input query conditions, define sql, obtain the pstmt object, set the value of ?, execute sql, Traverse Result to get data. It is necessary to manually encapsulate the result set and manually set the parameters. If there are many parameters, it is very cumbersome to set up every time. Registering the driver to obtain connections and SQL statements are a long string of strings, which are all hard-coded. If there is a slight change in the future, the code will be changed and the workload will be heavy.

2. Getting Started with MyBatis

1. Create a user table and add data

2. Create a module and import coordinates

3. Write the MyBatis core configuration file --> replace the connection information to solve the hard-coded problem

4. Write SQL mapping file --> Unified management of SQL statements to solve the problem of hard coding

5. Coding

            Ⅰ Define POJO class

            Ⅱ Load the core configuration file and get the SqlSessionFactory object

            Ⅲ Get the SqlSession object and execute the SQL statement

            ⅣRelease resources

1. Create a user table and add data

 

2. Create a module and import coordinates

Pom.xml dependencies:

<dependencies>
<!--        mybatis 依赖-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.5</version>
        </dependency>
<!--        mysql 驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.46</version>
        </dependency>

<!--        junit 单元测试-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13</version>
            <scope>test</scope>
        </dependency>

<!--        logback 日志依赖-->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.20</version>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.3</version>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-core</artifactId>
            <version>1.2.3</version>
        </dependency>
    </dependencies>

3. Write MyBatis core configuration file

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-config.dtd">
<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:///mybatis?useSSL=false"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
<!--        加载sql映射文件-->
        <mapper resource="UserMapper.xml"/>
    </mappers>
</configuration>

4. Write SQL mapping file

5. Coding

public static void main(String[] args) throws IOException {
        //1.加载mybatis的核心配置文件,获取SqlSessionFactory
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //2.获取SqlSession对象,用它来执行sql
        SqlSession sqlSession=sqlSessionFactory.openSession();
        //3.执行sql
        List<User> users=sqlSession.selectList("test.selectAll");
        //4.释放资源
        System.out.println(users);
    }

3. Mapper agent development

1. Define the Mapper interface with the same name as the SQL mapping file, and prevent the Mapper interface and the SQL mapping file from being in the same directory

Don't directly drag the xml file to the same folder as your interface file. Generally, xml should be placed in the resource. When we compile, the configuration file in the resource will be executed into the corresponding location, so we put it under the resource Create a package with the same name, but be careful not to use ".", replace it with "/"

Check whether it is in a directory after executing maven

2. Set the namespace attribute of the SQL mapping file to the fully qualified name of the Mapper interface

 3. Define the method in the Mapper interface, the method name is the id of the sql statement in the SQL mapping file, and keep the parameter type and return value type consistent

The path in mybatis-config.xml should also be changed accordingly, just copy the path

 4. Coding

        1. Obtain the proxy object of the Mapper interface through the getMapper method of SqlSession

        2. Call the corresponding method to complete the execution of sql

public static void main(String[] args) throws IOException {
        //1.加载mybatis的核心配置文件,获取SqlSessionFactory
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //获取SqlSession对象,用它来执行sql
        SqlSession sqlSession=sqlSessionFactory.openSession();
        //获取UserMapper接口的代理对象
        UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
        List<User> users=userMapper.selectAll();
        //4.释放资源
        for (int i=0;i< users.size();i++){
            System.out.println(users.get(i));
        }

    }

Guess you like

Origin blog.csdn.net/weixin_52479225/article/details/127951904