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


  • 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="" xmlns:xsi=""



//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) { = 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;

    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 "-// Mapper 3.0//EN" "">
<mapper namespace="userMapper">

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

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

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

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

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

<!--5.Preparation of core documents SqlMapConfig.xml-->
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-// Config 3.0//EN" "">

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

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

    <!--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}"/>

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

//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
//Release resources

Overview of Mybatis mapping file

Topics: Java Mybatis