Programming & Development / April 19, 2025

How to Use MyBatis Mapper with JdbcDataSource in Java (Step-by-Step)

MyBatis JdbcDataSource example MyBatis with H2 database Java MyBatis mapper annotations MyBatis JDBC setup MyBatis without XML configuration

πŸ“Œ Problem

You want to use MyBatis in Java with a JDBC-based DataSource (like H2, MySQL, PostgreSQL, etc.) to:

  • Configure the data source.
  • Define a mapper interface for SQL operations using annotations.
  • Insert and fetch data from the database with clean, readable code.

πŸš€ Solution Overview

We’ll use:

  • MyBatis (no XML configuration).
  • PooledDataSource for connection pooling.
  • A Mapper interface with @Select and @Insert.
  • A POJO class (User) to represent database records.

🧱 Step 1: Maven Dependencies

Add the following to your pom.xml:

xml

<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.7</version>
</dependency>
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <version>1.4.200</version>
</dependency>

Replace H2 with your actual DB driver if needed.

πŸ›  Step 2: Configure JdbcDataSource and MyBatis

java

import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import javax.sql.DataSource;

public class MyBatisUtil {

    private static SqlSessionFactory sqlSessionFactory;

    public static SqlSessionFactory getSqlSessionFactory() {
        if (sqlSessionFactory == null) {
            DataSource dataSource = new PooledDataSource(
                "org.h2.Driver",                // JDBC driver
                "jdbc:h2:mem:testdb",           // JDBC URL (in-memory)
                "sa",                           // DB username
                ""                              // DB password
            );

            sqlSessionFactory = new SqlSessionFactoryBuilder()
                .build(); // Normally, you load configuration here

            // Manually set data source (programmatic config)
            sqlSessionFactory.getConfiguration().setEnvironment(
                new org.apache.ibatis.mapping.Environment(
                    "development",
                    new org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory(),
                    dataSource
                )
            );
        }
        return sqlSessionFactory;
    }
}

πŸ’‘ Step 3: Define MyBatis Mapper Interface

java

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;

public interface UserMapper {

    @Select("SELECT id, name FROM users WHERE id = #{id}")
    User getUserById(int id);

    @Insert("INSERT INTO users (id, name) VALUES (#{id}, #{name})")
    void insertUser(User user);
}

πŸ‘€ Step 4: Create a User POJO

java

public class User {
    private int id;
    private String name;

    // Getters & Setters
    public int getId() { return id; }
    public void setId(int id) { this.id = id; }

    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
}

πŸ§ͺ Step 5: Insert and Fetch Data Using MyBatis

java

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

public class MyBatisExample {

    public static void main(String[] args) {
        SqlSessionFactory sqlSessionFactory = MyBatisUtil.getSqlSessionFactory();

        try (SqlSession session = sqlSessionFactory.openSession()) {

            // Create test table (H2 specific SQL)
            session.getConnection().createStatement().execute(
                "CREATE TABLE users (id INT PRIMARY KEY, name VARCHAR(255))"
            );

            UserMapper mapper = session.getMapper(UserMapper.class);

            // Insert new user
            User user = new User();
            user.setId(1);
            user.setName("Alice");
            mapper.insertUser(user);
            session.commit(); // Commit transaction

            // Fetch user by ID
            User fetched = mapper.getUserById(1);
            System.out.println("πŸ‘€ User fetched: " + fetched.getName());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

βœ… Output

sql

πŸ‘€ User fetched: Alice

🧠 Key Concepts

ComponentPurposePooledDataSourceJDBC connection pooling (optional but recommended)SqlSessionFactoryCreates sessions to interact with DB@Select, @InsertAnnotation-based SQL queriesSqlSession.commit()Ensures DML operations are saved

πŸ” Replace H2 with Your DB

To switch from H2 to another database:

  • Update PooledDataSource with the correct JDBC driver class, URL, username, and password.
  • Ensure the table (users) exists or modify the SQL.

πŸ›‘οΈ Best Practices

  • For real-world applications, use XML-based or Spring-integrated configurations for scalability.
  • Handle exceptions with a custom utility or logging framework (like SLF4J).
  • Avoid hardcoding SQL in annotations for complex queriesβ€”use XML mappers instead.



Comments

No comments yet

Add a new Comment

NUHMAN.COM

Information Technology website for Programming & Development, Web Design & UX/UI, Startups & Innovation, Gadgets & Consumer Tech, Cloud Computing & Enterprise Tech, Cybersecurity, Artificial Intelligence (AI) & Machine Learning (ML), Gaming Technology, Mobile Development, Tech News & Trends, Open Source & Linux, Data Science & Analytics

Categories

Tags

©{" "} Nuhmans.com . All Rights Reserved. Designed by{" "} HTML Codex