Getting Started with MyBatis: Understanding the Framework, Configuration, and CRUD Example in Java

This article introduces MyBatis as a lightweight persistence framework for Java, explains its history and core concepts, compares it with Hibernate, and provides a step‑by‑step guide with configuration files, entity classes, mapper interfaces, XML mappings, utility classes, and a test service to perform basic CRUD operations.

Java Captain
Java Captain
Java Captain
Getting Started with MyBatis: Understanding the Framework, Configuration, and CRUD Example in Java

MyBatis originated from Apache's iBatis project, moved to Google Code in 2010, and later to GitHub in 2013. It is a powerful persistence layer that supports plain SQL, stored procedures, and advanced mappings, eliminating most JDBC boilerplate by using XML or annotations to map POJOs to database tables.

1. Understanding What MyBatis Is

MyBatis provides a "semi‑automatic" ORM approach, focusing on the mapping between POJOs and SQL rather than full automatic entity‑to‑table mapping like Hibernate. It supports Java, .NET, and Ruby, but this guide concentrates on the Java implementation.

MyBatis offers a middle ground between manual JDBC code and fully automated ORM solutions, allowing developers to write SQL directly while handling result‑set mapping automatically.

2. Simple Example (Quick Start)

Step 1: Create a Java Web project.

Step 2: Add required MyBatis JARs. Required jars include mybatis-3.3.0.jar, mysql-connector-java-5.1.15-bin.jar, and log4j.jar.

Step 3: Create the MySQL database and table.

Step 4: Add MySQL driver configuration file.

Step 5: Add the MyBatis configuration file mybatis.cfg.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>
  <!-- Load external properties -->
  <properties resource="mysql.properties"/>
  <!-- Type aliases (auto‑scan) -->
  <typeAliases>
    <package name="com.cy.mybatis.beans"/>
  </typeAliases>
  <!-- Environment configuration -->
  <environments default="cybatis">
    <environment id="cybatis">
      <transactionManager type="JDBC"/>
      <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>
  <!-- Mapper registration (auto‑scan) -->
  <mappers>
    <package name="com/cy/mybatis/mapper"/>
  </mappers>
</configuration>

Step 6: Create the entity class UserBean.java .

package com.cy.mybatis.beans;

import java.io.Serializable;

public class UserBean implements Serializable {
    private static final long serialVersionUID = 1L;
    private Integer id;
    private String username;
    private String password;
    private Double account;
    // Constructors, getters, setters, and toString() omitted for brevity
}

Step 7: Define the mapper interface UserMapper.java and its XML mapping UserMapper.xml .

package com.cy.mybatis.mapper;

import java.util.List;
import com.cy.mybatis.beans.UserBean;

public interface UserMapper {
    int insertUser(UserBean user) throws Exception;
    int updateUser(UserBean user, int id) throws Exception;
    int deleteUser(int id) throws Exception;
    UserBean selectUserById(int id) throws Exception;
    List<UserBean> selectAllUser() throws Exception;
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org/DTD Mapper 3.0" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.cy.mybatis.mapper.UserMapper">
  <resultMap id="userMap" type="UserBean">
    <id property="id" column="id" javaType="java.lang.Integer"/>
    <result property="username" column="username" javaType="java.lang.String"/>
    <result property="password" column="password" javaType="java.lang.String"/>
    <result property="account" column="account" javaType="java.lang.Double"/>
  </resultMap>
  <insert id="insertUser" useGeneratedKeys="true" keyProperty="id">
    INSERT INTO t_user (username, password, account) VALUES (#{username}, #{password}, #{account})
  </insert>
  <update id="updateUser">
    UPDATE t_user SET username=#{username}, password=#{password}, account=#{account} WHERE id=#{id}
  </update>
  <delete id="deleteUser" parameterType="int">
    DELETE FROM t_user WHERE id=#{id}
  </delete>
  <select id="selectUserById" parameterType="int" resultMap="userMap">
    SELECT * FROM t_user WHERE id=#{id}
  </select>
  <select id="selectAllUser" resultMap="userMap">
    SELECT * FROM t_user
  </select>
</mapper>

Step 8: Create a utility class DBTools.java to obtain SqlSession instances.

package com.cy.mybatis.tools;

import java.io.Reader;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class DBTools {
    public static SqlSessionFactory sessionFactory;
    static {
        try {
            Reader reader = Resources.getResourceAsReader("mybatis.cfg.xml");
            sessionFactory = new SqlSessionFactoryBuilder().build(reader);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static SqlSession getSession() {
        return sessionFactory.openSession();
    }
}

Step 9: Write a test service UserService.java that demonstrates insert, delete, select by id, and select all operations.

package com.cy.mybatis.service;

import java.util.List;
import org.apache.ibatis.session.SqlSession;
import com.cy.mybatis.beans.UserBean;
import com.cy.mybatis.tools.DBTools;
import com.cy.mybatis.mapper.UserMapper;

public class UserService {
    public static void main(String[] args) {
        insertUser();
        // deleteUser();
        // selectUserById();
        // selectAllUser();
    }
    private static void insertUser() {
        SqlSession session = DBTools.getSession();
        UserMapper mapper = session.getMapper(UserMapper.class);
        UserBean user = new UserBean("懿", "1314520", 7000.0);
        try {
            mapper.insertUser(user);
            System.out.println(user);
            session.commit();
        } catch (Exception e) {
            e.printStackTrace();
            session.rollback();
        }
    }
    // deleteUser(), selectUserById(), selectAllUser() methods omitted for brevity
}

The test output shows the inserted record with the generated primary key, confirming that MyBatis correctly maps the Java object to the database row.

Overall, this guide provides a complete end‑to‑end example of using MyBatis in a Java backend project, covering project setup, configuration, entity definition, mapper creation, utility handling, and basic CRUD operations.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendJavaPersistenceMyBatisORMCRUD
Java Captain
Written by

Java Captain

Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.