Understanding MyBatis: From JDBC Basics to MyBatis Architecture and Initialization

This article explains how JDBC operations evolve into the MyBatis persistence framework, covering JDBC's seven-step query process, MyBatis's design components, initialization workflow, builder patterns, and includes practical Java code examples for each stage.

Top Architect
Top Architect
Top Architect
Understanding MyBatis: From JDBC Basics to MyBatis Architecture and Initialization

1. Introduction

The article introduces the gradual transition from raw JDBC to the MyBatis persistence framework, emphasizing why JDBC should be encapsulated into a higher‑level ORM solution.

2. JDBC Query Process

JDBC typically requires seven steps: loading the driver, obtaining a connection, creating a Statement, setting parameters, executing the SQL, processing the ResultSet, and finally releasing resources.

public static List<Map<String,Object>> queryForList(){
    Connection connection = null;
    ResultSet rs = null;
    PreparedStatement stmt = null;
    List<Map<String,Object>> resultList = new ArrayList<>();
    try{
        // Load driver
        Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
        String url = "jdbc:oracle:thin:@localhost:1521:ORACLEDB";
        String user = "trainer";
        String password = "trainer";
        // Get connection
        connection = DriverManager.getConnection(url,user,password);
        String sql = "select * from userinfo where user_id = ? ";
        stmt = connection.prepareStatement(sql);
        stmt.setString(1, "zhangsan");
        rs = stmt.executeQuery();
        ResultSetMetaData rsmd = rs.getMetaData();
        int num = rsmd.getColumnCount();
        while(rs.next()){
            Map map = new HashMap();
            for(int i=0;i<num;i++){
                String columnName = rsmd.getColumnName(i+1);
                map.put(columnName, rs.getString(columnName));
            }
            resultList.add(map);
        }
    }catch(Exception e){
        e.printStackTrace();
    }finally{
        try{ if(rs!=null) rs.close(); }catch(SQLException e){e.printStackTrace();}
        try{ if(stmt!=null) stmt.close(); }catch(SQLException e){e.printStackTrace();}
        try{ if(connection!=null) connection.close(); }catch(SQLException e){e.printStackTrace();}
    }
    return resultList;
}

3. From JDBC to MyBatis

Many of the seven JDBC steps can be abstracted away. The article proposes five optimization stages:

Connection acquisition and release using a connection pool (DataSource).

Centralizing SQL statements in configuration files or a database.

Parameter mapping and dynamic SQL generation.

Result mapping and caching.

Eliminating duplicate SQL by modularizing common fragments.

4. MyBatis Improvements

MyBatis still requires explicit SQL for most operations. The author suggests generating SQL automatically for single‑table CRUD via reflection on JavaBeans.

5. MyBatis Core Components

The framework consists of:

SqlSession : top‑level API for database interaction.

Executor : creates BoundSql, manages cache, and executes statements.

StatementHandler : prepares PreparedStatement, sets parameters, and invokes ResultSetHandler.

ParameterHandler : assigns values to ? placeholders.

ResultSetHandler : converts ResultSet into List or mapped objects.

Other supporting classes such as TypeHandler, MappedStatement, and Configuration.

6. SqlSession Workflow

SqlSession sqlSession = factory.openSession();
List<Employee> result = sqlSession.selectList("com.louis.mybatis.dao.EmployeesMapper.selectByMinSalary", params);

The selectList method looks up the MappedStatement by ID, delegates to the Executor, which builds the SQL, checks cache, prepares a Statement, and finally returns a List of results.

7. MyBatis Initialization

Initialization loads the XML configuration into a Configuration object via XMLConfigBuilder, parses sections such as properties, typeAliases, plugins, environments, and mappers. The environments element creates an Environment object using a builder pattern:

Environment env = new Environment.Builder(id)
    .transactionFactory(txFactory)
    .dataSource(dataSource)
    .build();
configuration.setEnvironment(env);

Finally, SqlSessionFactoryBuilder builds a DefaultSqlSessionFactory from the populated Configuration.

8. Design Patterns Used

MyBatis heavily employs the Builder pattern for constructing SqlSessionFactory, Environment, and other complex objects, as well as the Factory pattern for creating executors, handlers, and data sources.

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.

Design PatternsJavaSQLMyBatisJDBC
Top Architect
Written by

Top Architect

Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.

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.