MyBatis CRUD Operations Implementation Guide

Database Setup and Configuration

This guide demonstrtaes how to implement basic CRUD operations using MyBatis. We'll use a student management system as our example.

Database Initialization

CREATE DATABASE `test` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;

CREATE TABLE `student` (
    `id` INT NOT NULL AUTO_INCREMENT,
    `name` VARCHAR(20) NOT NULL,
    `age` INT NOT NULL,
    `score` DOUBLE NOT NULL,
    PRIMARY KEY (`id`)
) ENGINE = MyISAM;

Project Dependencies

<dependencies>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.3.0</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.29</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.11</version>
        <scope>test</scope>
    </dependency>
</dependencies>

Entity Class

package entity;

public class Student {
    private Integer studentId;
    private String studentName;
    private int studentAge;
    private double studentScore;
    
    public Student() {}
    
    public Student(String name, int age, double score) {
        this.studentName = name;
        this.studentAge = age;
        this.studentScore = score;
    }
    
    // Getters and setters
    public Integer getStudentId() { return studentId; }
    public void setStudentId(Integer id) { this.studentId = id; }
    public String getStudentName() { return studentName; }
    public void setStudentName(String name) { this.studentName = name; }
    public int getStudentAge() { return studentAge; }
    public void setStudentAge(int age) { this.studentAge = age; }
    public double getStudentScore() { return studentScore; }
    public void setStudentScore(double score) { this.studentScore = score; }
    
    @Override
    public String toString() {
        return "Student [id=" + studentId + ", name=" + studentName + 
               ", age=" + studentAge + ", score=" + studentScore + "]";
    }
}

MyBatis Configuration

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <properties resource="database.properties"/>
    
    <typeAliases>
        <package name="entity"/>
    </typeAliases>
    
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${db.driver}"/>
                <property name="url" value="${db.url}"/>
                <property name="username" value="${db.username}"/>
                <property name="password" value="${db.password}"/>
            </dataSource>
        </environment>
    </environments>
    
    <mappers>
        <mapper resource="mappers/StudentMapper.xml"/>
    </mappers>
</configuration>

Mapper XML File

<?xml version="1.0" encoding="UTF-8"?>
<mapper namespace="studentOperations">
    
    <insert id="addStudent" parameterType="Student">
        INSERT INTO student(name, age, score) 
        VALUES(#{studentName}, #{studentAge}, #{studentScore})
    </insert>
    
    <insert id="addStudentReturnId" parameterType="Student">
        INSERT INTO student(name, age, score) 
        VALUES(#{studentName}, #{studentAge}, #{studentScore})
        <selectKey resultType="int" keyProperty="studentId" order="AFTER">
            SELECT LAST_INSERT_ID()
        </selectKey>
    </insert>
    
    <delete id="removeStudent">
        DELETE FROM student WHERE id = #{identifier}
    </delete>
    
    <update id="modifyStudent" parameterType="Student">
        UPDATE student 
        SET name = #{studentName}, age = #{studentAge}, score = #{studentScore}
        WHERE id = #{studentId}
    </update>
    
    <select id="fetchAllStudents" resultType="Student">
        SELECT id as studentId, name as studentName, 
               age as studentAge, score as studentScore 
        FROM student
    </select>
    
    <select id="fetchStudentById" resultType="Student">
        SELECT * FROM student WHERE id = #{id}
    </select>
    
    <select id="searchStudentsByName" resultType="Student">
        SELECT id as studentId, name as studentName, 
               age as studentAge, score as studentScore 
        FROM student WHERE name LIKE CONCAT('%', #{searchTerm}, '%')
    </select>
</mapper>

DAO Interface

package persistence;

import entity.Student;
import java.util.List;
import java.util.Map;

public interface StudentRepository {
    void createStudent(Student student);
    void createStudentWithId(Student student);
    void removeStudent(int studentId);
    void updateStudent(Student student);
    List<Student> retrieveAllStudents();
    Map<String, Object> retrieveAllStudentsAsMap();
    Student retrieveStudentById(int studentId);
    List<Student> searchStudentsByName(String namePattern);
}

DAO Implementation

package persistence;

import entity.Student;
import org.apache.ibatis.session.SqlSession;
import utils.DatabaseSessionManager;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class StudentRepositoryImpl implements StudentRepository {
    private SqlSession databaseSession;
    
    public void createStudent(Student student) {
        try {
            databaseSession = DatabaseSessionManager.getSession();
            databaseSession.insert("studentOperations.addStudent", student);
            databaseSession.commit();
        } finally {
            if (databaseSession != null) databaseSession.close();
        }
    }
    
    public void createStudentWithId(Student student) {
        try {
            databaseSession = DatabaseSessionManager.getSession();
            databaseSession.insert("studentOperations.addStudentReturnId", student);
            databaseSession.commit();
        } finally {
            if (databaseSession != null) databaseSession.close();
        }
    }
    
    public void removeStudent(int studentId) {
        try {
            databaseSession = DatabaseSessionManager.getSession();
            databaseSession.delete("studentOperations.removeStudent", studentId);
            databaseSession.commit();
        } finally {
            if (databaseSession != null) databaseSession.close();
        }
    }
    
    public void updateStudent(Student student) {
        try {
            databaseSession = DatabaseSessionManager.getSession();
            databaseSession.update("studentOperations.modifyStudent", student);
            databaseSession.commit();
        } finally {
            if (databaseSession != null) databaseSession.close();
        }
    }
    
    public List<Student> retrieveAllStudents() {
        List<Student> students;
        try {
            databaseSession = DatabaseSessionManager.getSession();
            students = databaseSession.selectList("studentOperations.fetchAllStudents");
        } finally {
            if (databaseSession != null) databaseSession.close();
        }
        return students;
    }
    
    public Map<String, Object> retrieveAllStudentsAsMap() {
        Map<String, Object> studentMap = new HashMap<>();
        try {
            databaseSession = DatabaseSessionManager.getSession();
            studentMap = databaseSession.selectMap("studentOperations.fetchAllStudents", "studentName");
        } finally {
            if (databaseSession != null) databaseSession.close();
        }
        return studentMap;
    }
    
    public Student retrieveStudentById(int studentId) {
        Student student;
        try {
            databaseSession = DatabaseSessionManager.getSession();
            student = databaseSession.selectOne("studentOperations.fetchStudentById", studentId);
        } finally {
            if (databaseSession != null) databaseSession.close();
        }
        return student;
    }
    
    public List<Student> searchStudentsByName(String namePattern) {
        List<Student> students;
        try {
            databaseSession = DatabaseSessionManager.getSession();
            students = databaseSession.selectList("studentOperations.searchStudentsByName", namePattern);
        } finally {
            if (databaseSession != null) databaseSession.close();
        }
        return students;
    }
}

Session Management Utility

package utils;

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

public class DatabaseSessionManager {
    private static SqlSessionFactory sessionFactory;
    
    public static SqlSession getSession() {
        try {
            InputStream configStream = Resources.getResourceAsStream("mybatis-config.xml");
            if (sessionFactory == null) {
                sessionFactory = new SqlSessionFactoryBuilder().build(configStream);
            }
            return sessionFactory.openSession();
        } catch (Exception e) {
            throw new RuntimeException("Database session initialization failed", e);
        }
    }
}

Testing Implementation

import entity.Student;
import persistence.StudentRepository;
import persistence.StudentRepositoryImpl;
import org.junit.Before;
import org.junit.Test;
import java.util.List;
import java.util.Map;

public class StudentOperationsTest {
    private StudentRepository repository;
    
    @Before
    public void setup() {
        repository = new StudentRepositoryImpl();
    }
    
    @Test
    public void testStudentCreation() {
        Student newStudent = new Student("Test Student", 20, 85.5);
        System.out.println("Before creation: " + newStudent);
        repository.createStudent(newStudent);
        System.out.println("After creation: " + newStudent);
    }
    
    @Test
    public void testStudentCreationWithId() {
        Student student = new Student("Another Student", 22, 90.0);
        System.out.println("Before creation: " + student);
        repository.createStudentWithId(student);
        System.out.println("After creation: " + student);
    }
    
    @Test
    public void testStudentRemoval() {
        repository.removeStudent(5);
    }
    
    @Test
    public void testStudentUpdate() {
        Student student = new Student("Updated Name", 21, 95.0);
        student.setStudentId(3);
        repository.updateStudent(student);
    }
    
    @Test
    public void testRetrieveAllStudents() {
        List<Student> students = repository.retrieveAllStudents();
        for (Student student : students) {
            System.out.println(student);
        }
    }
    
    @Test
    public void testStudentRetrievalById() {
        Student student = repository.retrieveStudentById(2);
        System.out.println(student);
    }
    
    @Test
    public void testStudentSearchByName() {
        List<Student> students = repository.searchStudentsByName("test");
        for (Student student : students) {
            System.out.println(student);
        }
    }
}

MyBatis Execution Flow

  1. Load and parse MyBatis configuration file to obtain database connection details
  2. Scan configured mapper XML files for SQL statements
  3. Store SQL statements with their namespace and ID mappings
  4. Build SqlSessionFactory using data base connection information
  5. Execute SQL operasions through SqlSession methods (insert, update, delete, select)

Tags: MyBatis SQL Mapper Database Operations Java Persistence CRUD Operations

Posted on Mon, 14 Sep 2026 16:05:00 +0000 by patmcv