SQL mapping framework that eliminates JDBC boilerplate and couples objects with stored procedures or SQL statements using XML descriptors or annotations.
—
Core session and transaction management functionality in MyBatis. The SqlSession is the primary interface for all database operations, while SqlSessionFactory manages session creation and configuration.
Factory for creating SqlSession instances with various configuration options.
/**
* Creates SqlSession instances from configuration or DataSource
*/
interface SqlSessionFactory {
/** Open session with default settings (no autocommit) */
SqlSession openSession();
/** Open session with autocommit setting */
SqlSession openSession(boolean autoCommit);
/** Open session with specific connection */
SqlSession openSession(Connection connection);
/** Open session with transaction isolation level */
SqlSession openSession(TransactionIsolationLevel level);
/** Open session with executor type */
SqlSession openSession(ExecutorType execType);
/** Open session with executor type and autocommit */
SqlSession openSession(ExecutorType execType, boolean autoCommit);
/** Open session with executor type and isolation level */
SqlSession openSession(ExecutorType execType, TransactionIsolationLevel level);
/** Open session with executor type and connection */
SqlSession openSession(ExecutorType execType, Connection connection);
/** Get the configuration used by this factory */
Configuration getConfiguration();
}Usage Examples:
// Basic session creation
SqlSession session = sqlSessionFactory.openSession();
// Session with autocommit enabled
SqlSession autoCommitSession = sqlSessionFactory.openSession(true);
// Session with batch executor for bulk operations
SqlSession batchSession = sqlSessionFactory.openSession(ExecutorType.BATCH);
// Session with specific isolation level
SqlSession isolatedSession = sqlSessionFactory.openSession(TransactionIsolationLevel.REPEATABLE_READ);Builder for creating SqlSessionFactory instances from various configuration sources.
/**
* Builder for SqlSessionFactory instances
*/
class SqlSessionFactoryBuilder {
/** Build from XML configuration file reader */
SqlSessionFactory build(Reader reader);
/** Build from XML with specific environment */
SqlSessionFactory build(Reader reader, String environment);
/** Build from XML with properties override */
SqlSessionFactory build(Reader reader, Properties properties);
/** Build from XML reader with environment and properties */
SqlSessionFactory build(Reader reader, String environment, Properties properties);
/** Build from XML configuration input stream */
SqlSessionFactory build(InputStream inputStream);
/** Build from input stream with specific environment */
SqlSessionFactory build(InputStream inputStream, String environment);
/** Build from input stream with properties override */
SqlSessionFactory build(InputStream inputStream, Properties properties);
/** Build from input stream with environment and properties */
SqlSessionFactory build(InputStream inputStream, String environment, Properties properties);
/** Build from pre-configured Configuration object */
SqlSessionFactory build(Configuration config);
}Usage Examples:
// Build from XML configuration file
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
// Build with specific environment (for multi-environment configs)
SqlSessionFactory factory = new SqlSessionFactoryBuilder()
.build(inputStream, "production");
// Build with properties override
Properties props = new Properties();
props.setProperty("database.url", "jdbc:mysql://prod-server/db");
SqlSessionFactory factory = new SqlSessionFactoryBuilder()
.build(inputStream, props);Primary interface for executing SQL statements and managing transactions.
/**
* Primary interface for working with MyBatis. Execute commands, get mappers, manage transactions.
*/
interface SqlSession extends Closeable {
// Query operations
/** Retrieve single row mapped from statement key */
<T> T selectOne(String statement);
/** Retrieve single row with parameter */
<T> T selectOne(String statement, Object parameter);
/** Retrieve multiple rows */
<T> List<T> selectList(String statement);
/** Retrieve multiple rows with parameter */
<T> List<T> selectList(String statement, Object parameter);
/** Retrieve multiple rows with row bounds (pagination) */
<T> List<T> selectList(String statement, Object parameter, RowBounds rowBounds);
/** Retrieve cursor for large result sets */
<T> Cursor<T> selectCursor(String statement);
/** Retrieve cursor with parameter */
<T> Cursor<T> selectCursor(String statement, Object parameter);
/** Retrieve cursor with parameter and row bounds */
<T> Cursor<T> selectCursor(String statement, Object parameter, RowBounds rowBounds);
/** Stream results to custom handler */
void select(String statement, ResultHandler handler);
/** Stream results with parameter to custom handler */
void select(String statement, Object parameter, ResultHandler handler);
/** Stream results with parameter and row bounds to handler */
void select(String statement, Object parameter, RowBounds rowBounds, ResultHandler handler);
// Update operations
/** Execute insert statement */
int insert(String statement);
/** Execute insert with parameter */
int insert(String statement, Object parameter);
/** Execute update statement */
int update(String statement);
/** Execute update with parameter */
int update(String statement, Object parameter);
/** Execute delete statement */
int delete(String statement);
/** Execute delete with parameter */
int delete(String statement, Object parameter);
// Transaction management
/** Commit current transaction */
void commit();
/** Commit transaction with force flag */
void commit(boolean force);
/** Rollback current transaction */
void rollback();
/** Rollback transaction with force flag */
void rollback(boolean force);
/** Flush batch statements and return results */
List<BatchResult> flushStatements();
/** Close the session */
void close();
/** Clear local session cache */
void clearCache();
// Mapper management
/** Get type-safe mapper interface implementation */
<T> T getMapper(Class<T> type);
// Connection and configuration access
/** Get underlying database connection */
Connection getConnection();
/** Get configuration used by this session */
Configuration getConfiguration();
}Usage Examples:
try (SqlSession session = sqlSessionFactory.openSession()) {
// Direct SQL execution with statement ID
User user = session.selectOne("com.example.UserMapper.selectById", 1);
List<User> users = session.selectList("com.example.UserMapper.selectAll");
// Insert with auto-generated key
User newUser = new User("John", "john@example.com");
session.insert("com.example.UserMapper.insert", newUser);
// Update and delete operations
user.setEmail("newemail@example.com");
session.update("com.example.UserMapper.update", user);
session.delete("com.example.UserMapper.delete", user.getId());
// Commit all changes
session.commit();
}
// Using mapper interfaces (type-safe approach)
try (SqlSession session = sqlSessionFactory.openSession()) {
UserMapper mapper = session.getMapper(UserMapper.class);
List<User> activeUsers = mapper.findByStatus("ACTIVE");
User user = mapper.findById(1);
mapper.updateEmail(user.getId(), "updated@example.com");
session.commit();
}Efficient batch processing using BatchExecutor for bulk database operations.
/**
* Result of batch operation execution
*/
class BatchResult {
/** Get the mapped statement that was executed */
MappedStatement getMappedStatement();
/** Get the SQL statement that was executed */
String getSql();
/** Get the parameter objects used in the batch */
List<Object> getParameterObjects();
/** Get the update counts for each statement in the batch */
int[] getUpdateCounts();
}Usage Examples:
// Batch operations for improved performance
try (SqlSession session = sqlSessionFactory.openSession(ExecutorType.BATCH)) {
UserMapper mapper = session.getMapper(UserMapper.class);
// Execute multiple operations in batch
for (User user : userList) {
mapper.insert(user);
}
// Flush batch and get results
List<BatchResult> results = session.flushStatements();
session.commit();
// Check batch results
for (BatchResult result : results) {
int[] updateCounts = result.getUpdateCounts();
System.out.println("Batch executed " + updateCounts.length + " statements");
}
}Physical pagination support using RowBounds for limiting result sets.
/**
* Physical row bounds for pagination
*/
class RowBounds {
/** Default row bounds (no limits) */
public static final RowBounds DEFAULT = new RowBounds();
/** Create row bounds with offset and limit */
public RowBounds(int offset, int limit);
/** Get the offset (starting row) */
public int getOffset();
/** Get the limit (max number of rows) */
public int getLimit();
}Usage Examples:
try (SqlSession session = sqlSessionFactory.openSession()) {
// Paginated query - get 10 records starting from record 20
RowBounds rowBounds = new RowBounds(20, 10);
List<User> users = session.selectList("selectAllUsers", null, rowBounds);
// Using with mapper interface
UserMapper mapper = session.getMapper(UserMapper.class);
List<User> pagedUsers = mapper.findAll(rowBounds);
}/**
* Executor types for different execution strategies
*/
enum ExecutorType {
/** Simple executor - creates new PreparedStatement for each execution */
SIMPLE,
/** Reuse executor - reuses PreparedStatements when SQL matches */
REUSE,
/** Batch executor - batches all updates until flushStatements() is called */
BATCH
}
/**
* Transaction isolation levels
*/
enum TransactionIsolationLevel {
NONE(Connection.TRANSACTION_NONE),
READ_UNCOMMITTED(Connection.TRANSACTION_READ_UNCOMMITTED),
READ_COMMITTED(Connection.TRANSACTION_READ_COMMITTED),
REPEATABLE_READ(Connection.TRANSACTION_REPEATABLE_READ),
SERIALIZABLE(Connection.TRANSACTION_SERIALIZABLE);
}
/**
* Custom result handler for streaming large result sets
*/
interface ResultHandler<T> {
/** Handle each result row */
void handleResult(ResultContext<? extends T> resultContext);
}
/**
* Context information for result handling
*/
interface ResultContext<T> {
/** Get the current result object */
T getResultObject();
/** Get the current result count */
int getResultCount();
/** Check if processing should stop */
boolean isStopped();
/** Stop the result processing */
void stop();
}Install with Tessl CLI
npx tessl i tessl/maven-org-mybatis--mybatis