Introduction and quick start to Mybatis

Posted by reversenorm on Tue, 08 Feb 2022 14:29:40 +0100

Introduction to Mybatis

Original jdbc operation

Problems in the original jdbc development:

  • The frequent creation and release of database connections cause a waste of system resources, which affects the system performance

  • sql statements are hard coded in the code, which makes the code difficult to maintain. The actual application of sql may change greatly. sql changes need to change the java code

  • When querying, you need to manually encapsulate the data in the result set into the entity. When inserting, you need to manually set the data of the entity to the placeholder position of the sql statement

Solution:

  • Initialize connection resources using database connection pool
  • Extract sql statements into xml configuration file
  • Use reflection, introspection and other underlying technologies to automatically map attributes and fields between entities and tables

Overview of mybaits

  1. mybaits is an excellent persistence layer framework. It encapsulates the process of jdbc operating the database, so that developers only need to pay attention to sql itself, and do not need to spend energy to deal with the process code of jdbc, such as registering driver, creating connection, creating statement, manually setting parameters, result set retrieval and so on.
  2. mybaits configures various statements to be executed by means of xml or annotation, and generates the final executed sql statement by mapping java objects with the dynamic parameters of sql in the statement.
  3. Finally, the mybaits framework executes sql and maps the results to java objects and returns them. The ORM idea is adopted to solve the problem of entity and database mapping, encapsulate jdbc and shield the underlying access details of jdbc api, so that we can complete the persistence operation of database without dealing with jdbc api.

Mybaits framework is a persistence layer framework, also known as ORM framework; Mybaits is called semi-automatic ORM framework, and Hibernate is called fully automatic ORM framework;

Query with Mybaits framework, sql statements need to be written by developers, and the data encapsulation framework can be completed automatically; Using Hibernate framework for query action, sql statements do not need to be written, and data development does not need to be written by developers themselves;

mybaits quick start

MyBaits development steps

mybaits official website:

  1. Add coordinates for MyBaits
  2. Create user data table
  3. Write User entity class
  4. Write the mapping file user mapper xml
  5. Write the core file sqlmapconfig xml
  6. Write test class
<!--1.add to Mybatis Coordinates of-->
<?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>

  <groupId>com.itheima</groupId>
  <artifactId>itheima_mybatis_quick</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.32</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
    </dependencies>

</project>
//3. Create user entity class
package main.Java;

public class User {
	private int id;
    private String username;
    private String password;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}
<!--4.Write mapping file User Mapper.xml-->
<?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">
<mapper namespace="userMapper">

    <!--Delete operation-->
    <delete id="delete" parameterType="int">
        delete from user where id=#{abc}
    </delete>

    <!--Modify operation-->
    <update id="update" parameterType="com.itheima.domain.User">
        update user set username=#{username},password=#{password} where id=#{id}
    </update>

    <!--Insert operation-->
    <insert id="save" parameterType="com.itheima.domain.User">
        insert into user values(#{id},#{username},#{password})
    </insert>

    <!--Query operation-->
    <select id="findAll" resultType="user">
        select * from user
    </select>

    <!--according to id Make a query-->
    <select id="findById" resultType="user" parameterType="int">
        select * from user where id=#{id}
    </select>

</mapper>
<!--5.Preparation of core documents SqlMapConfig.xml-->
<?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>

    <!--adopt properties Label load external properties file-->
    <properties resource="jdbc.properties"></properties>

    <!--Custom alias-->
    <typeAliases>
        <typeAlias type="com.itheima.domain.User" alias="user"></typeAlias>
    </typeAliases>

    <!--Data source environment-->
    <environments default="developement">
        <environment id="developement">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>
    

    <!--Load mapping file-->
    <mappers>
        <mapper resource="com/itheima/mapper/UserMapper.xml"></mapper>
    </mappers>

</configuration>
//6. Write test class

//Load core profile
InputStream resourceAsStream = Resources.getRescourceAsStream("sqlMapConfig.xml");
//Get sqlSession factory object
sqlSessionFactory sqlSessionFactory = new sqlSessionFactoryBuilder().build(resourceAsStream);
//Get sqlSession object
SqlSession sqlSession = sqlSessionFactory.openSession();
//Execute sql statement
List<User> useList = sqlSession.selectList("userMapper.findAll");
//Print results
System.out.println(userList);
//Release resources
sqlSession.close();

Overview of Mybatis mapping file

Topics: Java Mybatis