π 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
ComponentPurposePooledDataSource
JDBC connection pooling (optional but recommended)SqlSessionFactory
Creates sessions to interact with DB@Select
, @Insert
Annotation-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.