MyBatis-Flex is an elegant enhancement framework for MyBatis providing type-safe query building, active record patterns, and comprehensive ORM capabilities
—
Direct database operations without entity classes using the Row and Db utilities. Ideal for dynamic queries, reporting, data migration, and working with unknown table structures where entity mapping is not feasible or desired.
Static utility class providing direct database operations without requiring entity classes or mapper interfaces. Supports schema-aware operations, multi-datasource environments, batch processing, and comprehensive CRUD operations.
/**
* Static utility class for entity-free database operations
* Provides comprehensive database access with Row objects
*/
public class Db {
// Environment and invoker management
public static RowMapperInvoker invoker();
public static RowMapperInvoker invoker(String environmentId);
// INSERT OPERATIONS
/**
* Insert row into table
* @param tableName table name
* @param row row data
* @return number of affected rows
*/
public static int insert(String tableName, Row row);
/**
* Insert row into schema.table
* @param schema database schema name
* @param tableName table name
* @param row row data
* @return number of affected rows
*/
public static int insert(String schema, String tableName, Row row);
/**
* Execute raw SQL insert
* @param sql SQL insert statement
* @param args SQL parameters
* @return number of affected rows
*/
public static int insertBySql(String sql, Object... args);
/**
* Batch insert rows
* @param tableName table name
* @param rows collection of rows
* @return array of update counts
*/
public static int[] insertBatch(String tableName, Collection<Row> rows);
/**
* Batch insert rows into schema.table
* @param schema database schema name
* @param tableName table name
* @param rows collection of rows
* @return array of update counts
*/
public static int[] insertBatch(String schema, String tableName, Collection<Row> rows);
/**
* Batch insert rows with batch size control
* @param tableName table name
* @param rows collection of rows
* @param batchSize number of rows per batch
* @return array of update counts
*/
public static int[] insertBatch(String tableName, Collection<Row> rows, int batchSize);
/**
* Batch insert rows into schema.table with batch size control
* @param schema database schema name
* @param tableName table name
* @param rows collection of rows
* @param batchSize number of rows per batch
* @return array of update counts
*/
public static int[] insertBatch(String schema, String tableName, Collection<Row> rows, int batchSize);
/**
* High-performance batch insert using first row's columns
* @param tableName table name
* @param rows list of rows
* @return number of affected rows
*/
public static int insertBatchWithFirstRowColumns(String tableName, List<Row> rows);
/**
* High-performance batch insert using first row's columns into schema.table
* @param schema database schema name
* @param tableName table name
* @param rows list of rows
* @return number of affected rows
*/
public static int insertBatchWithFirstRowColumns(String schema, String tableName, List<Row> rows);
// DELETE OPERATIONS
/**
* Execute raw SQL delete
* @param sql SQL delete statement
* @param args SQL parameters
* @return number of affected rows
*/
public static int deleteBySql(String sql, Object... args);
/**
* Delete by primary key
* @param tableName table name
* @param row row with primary key values
* @return number of affected rows
*/
public static int deleteById(String tableName, Row row);
/**
* Delete by primary key from schema.table
* @param schema database schema name
* @param tableName table name
* @param row row with primary key values
* @return number of affected rows
*/
public static int deleteById(String schema, String tableName, Row row);
/**
* Delete by single primary key
* @param tableName table name
* @param primaryKey primary key column name
* @param id primary key value
* @return number of affected rows
*/
public static int deleteById(String tableName, String primaryKey, Object id);
/**
* Delete by single primary key from schema.table
* @param schema database schema name
* @param tableName table name
* @param primaryKey primary key column name
* @param id primary key value
* @return number of affected rows
*/
public static int deleteById(String schema, String tableName, String primaryKey, Object id);
/**
* Batch delete by primary key values
* @param tableName table name
* @param primaryKey primary key column name
* @param ids collection of primary key values
* @return number of affected rows
*/
public static int deleteBatchByIds(String tableName, String primaryKey, Collection<?> ids);
/**
* Batch delete by primary key values from schema.table
* @param schema database schema name
* @param tableName table name
* @param primaryKey primary key column name
* @param ids collection of primary key values
* @return number of affected rows
*/
public static int deleteBatchByIds(String schema, String tableName, String primaryKey, Collection<?> ids);
/**
* Delete by Map-based WHERE conditions
* @param tableName table name
* @param whereColumns map of column-value pairs for WHERE clause
* @return number of affected rows
*/
public static int deleteByMap(String tableName, Map<String, Object> whereColumns);
/**
* Delete by Map-based WHERE conditions from schema.table
* @param schema database schema name
* @param tableName table name
* @param whereColumns map of column-value pairs for WHERE clause
* @return number of affected rows
*/
public static int deleteByMap(String schema, String tableName, Map<String, Object> whereColumns);
/**
* Delete by QueryCondition
* @param tableName table name
* @param condition query condition
* @return number of affected rows
*/
public static int deleteByCondition(String tableName, QueryCondition condition);
/**
* Delete by QueryCondition from schema.table
* @param schema database schema name
* @param tableName table name
* @param condition query condition
* @return number of affected rows
*/
public static int deleteByCondition(String schema, String tableName, QueryCondition condition);
/**
* Delete by QueryWrapper
* @param tableName table name
* @param queryWrapper query wrapper with conditions
* @return number of affected rows
*/
public static int deleteByQuery(String tableName, QueryWrapper queryWrapper);
/**
* Delete by QueryWrapper from schema.table
* @param schema database schema name
* @param tableName table name
* @param queryWrapper query wrapper with conditions
* @return number of affected rows
*/
public static int deleteByQuery(String schema, String tableName, QueryWrapper queryWrapper);
// UPDATE OPERATIONS
/**
* Execute raw SQL update
* @param sql SQL update statement
* @param args SQL parameters
* @return number of affected rows
*/
public static int updateBySql(String sql, Object... args);
/**
* Batch update using SQL with parameter setter
* @param sql SQL update statement
* @param batchArgsSetter batch arguments setter
* @return array of update counts
*/
public static int[] updateBatch(String sql, BatchArgsSetter batchArgsSetter);
/**
* Update by primary key
* @param tableName table name
* @param row row with primary key and update data
* @return number of affected rows
*/
public static int updateById(String tableName, Row row);
/**
* Update by primary key in schema.table
* @param schema database schema name
* @param tableName table name
* @param row row with primary key and update data
* @return number of affected rows
*/
public static int updateById(String schema, String tableName, Row row);
/**
* Update by Map-based WHERE conditions
* @param tableName table name
* @param data row with update data
* @param whereColumns map of column-value pairs for WHERE clause
* @return number of affected rows
*/
public static int updateByMap(String tableName, Row data, Map<String, Object> whereColumns);
/**
* Update by Map-based WHERE conditions in schema.table
* @param schema database schema name
* @param tableName table name
* @param data row with update data
* @param whereColumns map of column-value pairs for WHERE clause
* @return number of affected rows
*/
public static int updateByMap(String schema, String tableName, Row data, Map<String, Object> whereColumns);
/**
* Update by QueryCondition
* @param tableName table name
* @param data row with update data
* @param condition query condition
* @return number of affected rows
*/
public static int updateByCondition(String tableName, Row data, QueryCondition condition);
/**
* Update by QueryCondition in schema.table
* @param schema database schema name
* @param tableName table name
* @param data row with update data
* @param condition query condition
* @return number of affected rows
*/
public static int updateByCondition(String schema, String tableName, Row data, QueryCondition condition);
/**
* Update by QueryWrapper
* @param tableName table name
* @param data row with update data
* @param queryWrapper query wrapper with conditions
* @return number of affected rows
*/
public static int updateByQuery(String tableName, Row data, QueryWrapper queryWrapper);
/**
* Update by QueryWrapper in schema.table
* @param schema database schema name
* @param tableName table name
* @param data row with update data
* @param queryWrapper query wrapper with conditions
* @return number of affected rows
*/
public static int updateByQuery(String schema, String tableName, Row data, QueryWrapper queryWrapper);
/**
* Batch update by primary keys
* @param tableName table name
* @param rows list of rows with primary keys and update data
* @return number of affected rows
*/
public static int updateBatchById(String tableName, List<Row> rows);
/**
* Batch update by primary keys in schema.table
* @param schema database schema name
* @param tableName table name
* @param rows list of rows with primary keys and update data
* @return number of affected rows
*/
public static int updateBatchById(String schema, String tableName, List<Row> rows);
/**
* Batch update entities with batch size control
* @param entities collection of entities
* @param batchSize batch size
* @return number of affected rows
*/
public static <T> int updateEntitiesBatch(Collection<T> entities, int batchSize);
/**
* Batch update entities with default batch size
* @param entities collection of entities
* @return number of affected rows
*/
public static <T> int updateEntitiesBatch(Collection<T> entities);
// SELECT OPERATIONS
/**
* Execute raw SQL select query
* @param sql SQL query string
* @param args query parameters
* @return single Row object or null
*/
public static Row selectOneBySql(String sql, Object... args);
/**
* Select one row by primary key
* @param tableName table name
* @param row row with primary key values
* @return single Row object or null
*/
public static Row selectOneById(String tableName, Row row);
/**
* Select one row by primary key from schema.table
* @param schema database schema name
* @param tableName table name
* @param row row with primary key values
* @return single Row object or null
*/
public static Row selectOneById(String schema, String tableName, Row row);
/**
* Select one row by single primary key
* @param tableName table name
* @param primaryKey primary key column name
* @param id primary key value
* @return single Row object or null
*/
public static Row selectOneById(String tableName, String primaryKey, Object id);
/**
* Select one row by single primary key from schema.table
* @param schema database schema name
* @param tableName table name
* @param primaryKey primary key column name
* @param id primary key value
* @return single Row object or null
*/
public static Row selectOneById(String schema, String tableName, String primaryKey, Object id);
/**
* Select one row by Map-based conditions
* @param tableName table name
* @param whereColumns map of column-value pairs for WHERE clause
* @return single Row object or null
*/
public static Row selectOneByMap(String tableName, Map whereColumns);
/**
* Select one row by Map-based conditions from schema.table
* @param schema database schema name
* @param tableName table name
* @param whereColumns map of column-value pairs for WHERE clause
* @return single Row object or null
*/
public static Row selectOneByMap(String schema, String tableName, Map whereColumns);
/**
* Select one row by QueryCondition
* @param tableName table name
* @param condition query condition
* @return single Row object or null
*/
public static Row selectOneByCondition(String tableName, QueryCondition condition);
/**
* Select one row by QueryCondition from schema.table
* @param schema database schema name
* @param tableName table name
* @param condition query condition
* @return single Row object or null
*/
public static Row selectOneByCondition(String schema, String tableName, QueryCondition condition);
/**
* Select one row by QueryWrapper
* @param tableName table name
* @param queryWrapper query wrapper with conditions
* @return single Row object or null
*/
public static Row selectOneByQuery(String tableName, QueryWrapper queryWrapper);
/**
* Select one row by QueryWrapper from schema.table
* @param schema database schema name
* @param tableName table name
* @param queryWrapper query wrapper with conditions
* @return single Row object or null
*/
public static Row selectOneByQuery(String schema, String tableName, QueryWrapper queryWrapper);
/**
* Select one row by QueryWrapper with table included
* @param queryWrapper query wrapper with FROM clause
* @return single Row object or null
*/
public static Row selectOneByQuery(QueryWrapper queryWrapper);
/**
* Execute raw SQL select query returning multiple rows
* @param sql SQL query string
* @param args query parameters
* @return list of Row objects
*/
public static List<Row> selectListBySql(String sql, Object... args);
/**
* Select rows by Map-based conditions
* @param tableName table name
* @param whereColumns map of column-value pairs for WHERE clause
* @return list of Row objects
*/
public static List<Row> selectListByMap(String tableName, Map<String, Object> whereColumns);
/**
* Select rows by Map-based conditions from schema.table
* @param schema database schema name
* @param tableName table name
* @param whereColumns map of column-value pairs for WHERE clause
* @return list of Row objects
*/
public static List<Row> selectListByMap(String schema, String tableName, Map<String, Object> whereColumns);
/**
* Select rows by Map-based conditions with limit
* @param tableName table name
* @param whereColumns map of column-value pairs for WHERE clause
* @param count maximum number of rows to return
* @return list of Row objects
*/
public static List<Row> selectListByMap(String tableName, Map<String, Object> whereColumns, Long count);
/**
* Select rows by Map-based conditions with limit from schema.table
* @param schema database schema name
* @param tableName table name
* @param whereColumns map of column-value pairs for WHERE clause
* @param count maximum number of rows to return
* @return list of Row objects
*/
public static List<Row> selectListByMap(String schema, String tableName, Map<String, Object> whereColumns, Long count);
/**
* Select rows by QueryCondition
* @param tableName table name
* @param condition query condition
* @return list of Row objects
*/
public static List<Row> selectListByCondition(String tableName, QueryCondition condition);
/**
* Select rows by QueryCondition from schema.table
* @param schema database schema name
* @param tableName table name
* @param condition query condition
* @return list of Row objects
*/
public static List<Row> selectListByCondition(String schema, String tableName, QueryCondition condition);
/**
* Select rows by QueryCondition with limit
* @param tableName table name
* @param condition query condition
* @param count maximum number of rows to return
* @return list of Row objects
*/
public static List<Row> selectListByCondition(String tableName, QueryCondition condition, Long count);
/**
* Select rows by QueryCondition with limit from schema.table
* @param schema database schema name
* @param tableName table name
* @param condition query condition
* @param count maximum number of rows to return
* @return list of Row objects
*/
public static List<Row> selectListByCondition(String schema, String tableName, QueryCondition condition, Long count);
/**
* Select rows by QueryWrapper
* @param tableName table name
* @param queryWrapper query wrapper with conditions
* @return list of Row objects
*/
public static List<Row> selectListByQuery(String tableName, QueryWrapper queryWrapper);
/**
* Select rows by QueryWrapper from schema.table
* @param schema database schema name
* @param tableName table name
* @param queryWrapper query wrapper with conditions
* @return list of Row objects
*/
public static List<Row> selectListByQuery(String schema, String tableName, QueryWrapper queryWrapper);
/**
* Select rows by QueryWrapper with table included
* @param queryWrapper query wrapper with FROM clause
* @return list of Row objects
*/
public static List<Row> selectListByQuery(QueryWrapper queryWrapper);
/**
* Select all rows from table
* @param tableName table name
* @return list of all rows
*/
public static List<Row> selectAll(String tableName);
/**
* Select all rows from schema.table
* @param schema database schema name
* @param tableName table name
* @return list of all rows
*/
public static List<Row> selectAll(String schema, String tableName);
// OBJECT SELECTION OPERATIONS
/**
* Select single object value from SQL query (1 row, 1 column)
* @param sql SQL query string
* @param args query parameters
* @return single object value
*/
public static Object selectObject(String sql, Object... args);
/**
* Select single object value by QueryWrapper from table
* @param tableName table name
* @param queryWrapper query wrapper
* @return single object value
*/
public static Object selectObject(String tableName, QueryWrapper queryWrapper);
/**
* Select single object value by QueryWrapper from schema.table
* @param schema database schema name
* @param tableName table name
* @param queryWrapper query wrapper
* @return single object value
*/
public static Object selectObject(String schema, String tableName, QueryWrapper queryWrapper);
/**
* Select single object value by QueryWrapper with table included
* @param queryWrapper query wrapper with FROM clause
* @return single object value
*/
public static Object selectObject(QueryWrapper queryWrapper);
/**
* Select first and second columns as Map (key-value pairs)
* @param sql SQL query string
* @param args query parameters
* @return Map with first column as keys, second column as values
*/
public static Map selectFirstAndSecondColumnsAsMap(String sql, Object... args);
/**
* Select first and second columns as Map by QueryWrapper from table
* @param tableName table name
* @param queryWrapper query wrapper
* @return Map with first column as keys, second column as values
*/
public static Map selectFirstAndSecondColumnsAsMap(String tableName, QueryWrapper queryWrapper);
/**
* Select first and second columns as Map by QueryWrapper from schema.table
* @param schema database schema name
* @param tableName table name
* @param queryWrapper query wrapper
* @return Map with first column as keys, second column as values
*/
public static Map selectFirstAndSecondColumnsAsMap(String schema, String tableName, QueryWrapper queryWrapper);
/**
* Select first and second columns as Map by QueryWrapper with table included
* @param queryWrapper query wrapper with FROM clause
* @return Map with first column as keys, second column as values
*/
public static Map selectFirstAndSecondColumnsAsMap(QueryWrapper queryWrapper);
/**
* Select multiple object values from SQL query (multiple rows, 1 column)
* @param sql SQL query string
* @param args query parameters
* @return list of object values
*/
public static List<Object> selectObjectList(String sql, Object... args);
/**
* Select multiple object values by QueryWrapper from table
* @param tableName table name
* @param queryWrapper query wrapper
* @return list of object values
*/
public static List<Object> selectObjectList(String tableName, QueryWrapper queryWrapper);
/**
* Select multiple object values by QueryWrapper from schema.table
* @param schema database schema name
* @param tableName table name
* @param queryWrapper query wrapper
* @return list of object values
*/
public static List<Object> selectObjectList(String schema, String tableName, QueryWrapper queryWrapper);
/**
* Select multiple object values by QueryWrapper with table included
* @param queryWrapper query wrapper with FROM clause
* @return list of object values
*/
public static List<Object> selectObjectList(QueryWrapper queryWrapper);
// COUNT OPERATIONS
/**
* Execute count query using SQL
* @param sql SQL count query
* @param args query parameters
* @return count value
*/
public static long selectCount(String sql, Object... args);
/**
* Count rows by QueryCondition
* @param tableName table name
* @param condition query condition
* @return count value
*/
public static long selectCountByCondition(String tableName, QueryCondition condition);
/**
* Count rows by QueryCondition from schema.table
* @param schema database schema name
* @param tableName table name
* @param condition query condition
* @return count value
*/
public static long selectCountByCondition(String schema, String tableName, QueryCondition condition);
/**
* Count rows by QueryWrapper
* @param tableName table name
* @param queryWrapper query wrapper with conditions
* @return count value
*/
public static long selectCountByQuery(String tableName, QueryWrapper queryWrapper);
/**
* Count rows by QueryWrapper from schema.table
* @param schema database schema name
* @param tableName table name
* @param queryWrapper query wrapper with conditions
* @return count value
*/
public static long selectCountByQuery(String schema, String tableName, QueryWrapper queryWrapper);
/**
* Count rows by QueryWrapper with table included
* @param queryWrapper query wrapper with FROM clause
* @return count value
*/
public static long selectCountByQuery(QueryWrapper queryWrapper);
// PAGINATION OPERATIONS
/**
* Paginate results by QueryCondition
* @param tableName table name
* @param pageNumber current page number (1-based)
* @param pageSize number of rows per page
* @param condition query condition
* @return Page object with results
*/
public static Page<Row> paginate(String tableName, Number pageNumber, Number pageSize, QueryCondition condition);
/**
* Paginate results by QueryCondition from schema.table
* @param schema database schema name
* @param tableName table name
* @param pageNumber current page number (1-based)
* @param pageSize number of rows per page
* @param condition query condition
* @return Page object with results
*/
public static Page<Row> paginate(String schema, String tableName, Number pageNumber, Number pageSize, QueryCondition condition);
/**
* Paginate results by QueryCondition with total count provided
* @param tableName table name
* @param pageNumber current page number (1-based)
* @param pageSize number of rows per page
* @param totalRow total number of rows (skips count query if provided)
* @param condition query condition
* @return Page object with results
*/
public static Page<Row> paginate(String tableName, Number pageNumber, Number pageSize, Number totalRow, QueryCondition condition);
/**
* Paginate results by QueryCondition with total count provided from schema.table
* @param schema database schema name
* @param tableName table name
* @param pageNumber current page number (1-based)
* @param pageSize number of rows per page
* @param totalRow total number of rows (skips count query if provided)
* @param condition query condition
* @return Page object with results
*/
public static Page<Row> paginate(String schema, String tableName, Number pageNumber, Number pageSize, Number totalRow, QueryCondition condition);
/**
* Paginate results by QueryWrapper
* @param tableName table name
* @param pageNumber current page number (1-based)
* @param pageSize number of rows per page
* @param queryWrapper query wrapper with conditions
* @return Page object with results
*/
public static Page<Row> paginate(String tableName, Number pageNumber, Number pageSize, QueryWrapper queryWrapper);
/**
* Paginate results by QueryWrapper from schema.table
* @param schema database schema name
* @param tableName table name
* @param pageNumber current page number (1-based)
* @param pageSize number of rows per page
* @param queryWrapper query wrapper with conditions
* @return Page object with results
*/
public static Page<Row> paginate(String schema, String tableName, Number pageNumber, Number pageSize, QueryWrapper queryWrapper);
/**
* Paginate results by QueryWrapper with total count provided
* @param tableName table name
* @param pageNumber current page number (1-based)
* @param pageSize number of rows per page
* @param totalRow total number of rows (skips count query if provided)
* @param queryWrapper query wrapper with conditions
* @return Page object with results
*/
public static Page<Row> paginate(String tableName, Number pageNumber, Number pageSize, Number totalRow, QueryWrapper queryWrapper);
/**
* Paginate results by QueryWrapper with total count provided from schema.table
* @param schema database schema name
* @param tableName table name
* @param pageNumber current page number (1-based)
* @param pageSize number of rows per page
* @param totalRow total number of rows (skips count query if provided)
* @param queryWrapper query wrapper with conditions
* @return Page object with results
*/
public static Page<Row> paginate(String schema, String tableName, Number pageNumber, Number pageSize, Number totalRow, QueryWrapper queryWrapper);
/**
* Paginate results using Page object
* @param tableName table name
* @param page page configuration (with totalCount for optimization)
* @param queryWrapper query wrapper with conditions
* @return Page object with results
*/
public static Page<Row> paginate(String tableName, Page<Row> page, QueryWrapper queryWrapper);
/**
* Paginate results using Page object from schema.table
* @param schema database schema name
* @param tableName table name
* @param page page configuration (with totalCount for optimization)
* @param queryWrapper query wrapper with conditions
* @return Page object with results
*/
public static Page<Row> paginate(String schema, String tableName, Page<Row> page, QueryWrapper queryWrapper);
// BATCH EXECUTION UTILITIES
/**
* Generic batch execution with total size and batch size control
* @param totalSize total number of operations
* @param batchSize number of operations per batch
* @param mapperClass mapper class to use
* @param consumer operation consumer
* @return array of execution results
*/
public static <M> int[] executeBatch(int totalSize, int batchSize, Class<M> mapperClass, BiConsumer<M, Integer> consumer);
/**
* Generic batch execution with data collection
* @param datas collection of data items
* @param mapperClass mapper class to use
* @param consumer operation consumer
* @return array of execution results
*/
public static <M, D> int[] executeBatch(Collection<D> datas, Class<M> mapperClass, BiConsumer<M, D> consumer);
/**
* Generic batch execution with data collection and batch size control
* @param datas collection of data items
* @param batchSize number of items per batch
* @param mapperClass mapper class to use
* @param consumer operation consumer
* @return array of execution results
*/
public static <M, E> int[] executeBatch(Collection<E> datas, int batchSize, Class<M> mapperClass, BiConsumer<M, E> consumer);
// TRANSACTION OPERATIONS
/**
* Execute operation in transaction (returns false/null or throws exception to rollback)
* @param supplier operation that returns boolean result
* @return true if transaction committed successfully
*/
public static boolean tx(Supplier<Boolean> supplier);
/**
* Execute operation in transaction with propagation control
* @param supplier operation that returns boolean result
* @param propagation transaction propagation behavior
* @return true if transaction committed successfully
*/
public static boolean tx(Supplier<Boolean> supplier, Propagation propagation);
/**
* Execute operation in transaction and return result (only rollback on exception)
* @param supplier operation that returns result
* @return operation result
*/
public static <T> T txWithResult(Supplier<T> supplier);
/**
* Execute operation in transaction with propagation control and return result
* @param supplier operation that returns result
* @param propagation transaction propagation behavior
* @return operation result
*/
public static <T> T txWithResult(Supplier<T> supplier, Propagation propagation);
}Comprehensive Insert Operations:
import com.mybatisflex.core.row.Db;
import com.mybatisflex.core.row.Row;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.core.paginate.Page;
import java.util.*;
public class DbOperationsExample {
public void demonstrateInsertOperations() {
// Basic insert operations
Row userRow = Row.ofMap(Map.of(
"name", "Alice",
"age", 25,
"email", "alice@example.com",
"active", true
));
int inserted = Db.insert("users", userRow);
// Schema-aware insert
int insertedWithSchema = Db.insert("public", "users", userRow);
// Raw SQL insert
int sqlInserted = Db.insertBySql(
"INSERT INTO users (name, age, email) VALUES (?, ?, ?)",
"Diana", 32, "diana@example.com"
);
// Batch insert with different approaches
List<Row> userRows = Arrays.asList(
Row.ofMap(Map.of("name", "Bob", "age", 30, "email", "bob@example.com")),
Row.ofMap(Map.of("name", "Charlie", "age", 28, "email", "charlie@example.com"))
);
// Standard batch insert
int[] batchResults = Db.insertBatch("users", userRows);
// Batch insert with custom batch size
int[] controlledBatch = Db.insertBatch("users", userRows, 500);
// High-performance batch insert (uses first row's columns)
int highPerfBatch = Db.insertBatchWithFirstRowColumns("users", userRows);
// Schema-aware batch operations
int[] schemaBatch = Db.insertBatch("public", "users", userRows, 1000);
}
}Flexible data structure representing a database row with Map-like interface for dynamic column access.
/**
* Represents a database row with flexible column access
*/
public class Row extends LinkedHashMap<String, Object> {
/**
* Create Row from Map
* @param map source map with column-value pairs
* @return new Row instance
*/
public static Row ofMap(Map<String, Object> map);
/**
* Create empty Row
* @return new empty Row instance
*/
public static Row create();
/**
* Set column value
* @param column column name
* @param value column value
* @return this Row for chaining
*/
public Row set(String column, Object value);
/**
* Get column value
* @param column column name
* @return column value
*/
public Object get(String column);
/**
* Get column value with type casting
* @param column column name
* @param clazz target type class
* @return typed column value
*/
public <T> T get(String column, Class<T> clazz);
/**
* Get string value
* @param column column name
* @return string value or null
*/
public String getString(String column);
/**
* Get integer value
* @param column column name
* @return integer value or null
*/
public Integer getInt(String column);
/**
* Get long value
* @param column column name
* @return long value or null
*/
public Long getLong(String column);
/**
* Get boolean value
* @param column column name
* @return boolean value or null
*/
public Boolean getBoolean(String column);
/**
* Get date value
* @param column column name
* @return date value or null
*/
public Date getDate(String column);
/**
* Check if column exists
* @param column column name
* @return true if column exists
*/
public boolean hasColumn(String column);
/**
* Remove column
* @param column column name
* @return removed value
*/
public Object remove(String column);
/**
* Convert to Map
* @return Map representation
*/
public Map<String, Object> toMap();
}Row Usage Examples:
public void demonstrateRowOperations() {
// Create Row from Map
Row user = Row.ofMap(Map.of(
"id", 1L,
"name", "Alice",
"age", 25,
"email", "alice@example.com",
"active", true,
"create_time", new Date()
));
// Create Row with chaining
Row product = Row.create()
.set("name", "Laptop")
.set("price", 999.99)
.set("category", "Electronics")
.set("in_stock", true);
// Type-safe value retrieval
String name = user.getString("name");
Integer age = user.getInt("age");
Boolean active = user.getBoolean("active");
Date createTime = user.getDate("create_time");
// Generic type casting
Long id = user.get("id", Long.class);
Double price = product.get("price", Double.class);
// Check column existence
if (user.hasColumn("email")) {
String email = user.getString("email");
System.out.println("Email: " + email);
}
// Convert back to Map
Map<String, Object> userMap = user.toMap();
}Comprehensive delete operations with multiple condition types and schema support.
Delete Examples:
public void demonstrateDeleteOperations() {
// Raw SQL delete
int deleted = Db.deleteBySql(
"DELETE FROM users WHERE active = ? AND last_login < ?",
false, thirtyDaysAgo
);
// Delete by primary key (Row)
Row pkRow = Row.ofKey(RowKey.of("id"), 123L);
int deletedById = Db.deleteById("users", pkRow);
// Delete by single primary key
int singlePkDelete = Db.deleteById("users", "id", 123L);
// Schema-aware delete
int schemaDelete = Db.deleteById("public", "users", "id", 123L);
// Batch delete by IDs
List<Long> idsToDelete = Arrays.asList(1L, 2L, 3L, 4L);
int batchDeleted = Db.deleteBatchByIds("users", "id", idsToDelete);
// Delete by Map conditions
Map<String, Object> deleteConditions = Map.of(
"active", false,
"account_type", "trial"
);
int mapDeleted = Db.deleteByMap("users", deleteConditions);
// Delete by QueryCondition
QueryCondition condition = USER.AGE.ge(65).and(USER.LAST_LOGIN.lt(sixMonthsAgo));
int conditionDeleted = Db.deleteByCondition("users", condition);
// Delete by QueryWrapper
QueryWrapper deleteQuery = QueryWrapper.create()
.where(USER.ACTIVE.eq(false))
.and(USER.CREATED_TIME.lt(oneYearAgo));
int queryDeleted = Db.deleteByQuery("users", deleteQuery);
}Comprehensive update operations with various condition types and batch support.
Update Examples:
public void demonstrateUpdateOperations() {
// Raw SQL update
int updated = Db.updateBySql(
"UPDATE users SET age = ?, last_login = ? WHERE id = ?",
26, new Date(), 1L
);
// Update by primary key
Row updateRow = Row.create()
.set("id", 1L) // Primary key
.set("name", "Alice Updated")
.set("email", "alice.updated@example.com")
.set("last_modified", new Date());
int pkUpdated = Db.updateById("users", updateRow);
// Schema-aware update
int schemaUpdated = Db.updateById("public", "users", updateRow);
// Update by Map conditions
Row updateData = Row.create()
.set("status", "verified")
.set("verified_date", new Date());
Map<String, Object> whereConditions = Map.of(
"email_verified", true,
"account_type", "premium"
);
int mapUpdated = Db.updateByMap("users", updateData, whereConditions);
// Update by QueryCondition
QueryCondition condition = USER.AGE.ge(18).and(USER.ACTIVE.eq(true));
Row adultUserUpdate = Row.create().set("adult_flag", true);
int conditionUpdated = Db.updateByCondition("users", adultUserUpdate, condition);
// Update by QueryWrapper
QueryWrapper updateQuery = QueryWrapper.create()
.where(USER.LAST_LOGIN.lt(thirtyDaysAgo))
.and(USER.ACTIVE.eq(true));
Row inactiveUpdate = Row.create().set("status", "inactive");
int queryUpdated = Db.updateByQuery("users", inactiveUpdate, updateQuery);
// Batch update by primary keys
List<Row> batchUpdateRows = Arrays.asList(
Row.create().set("id", 1L).set("status", "active"),
Row.create().set("id", 2L).set("status", "inactive"),
Row.create().set("id", 3L).set("status", "pending")
);
int batchUpdated = Db.updateBatchById("users", batchUpdateRows);
// Schema-aware batch update
int schemaBatchUpdated = Db.updateBatchById("public", "users", batchUpdateRows);
}Advanced select operations with multiple approaches and schema support.
Select Examples:
public void demonstrateSelectOperations() {
// Raw SQL select returning Rows
List<Row> users = Db.selectListBySql(
"SELECT id, name, age, email FROM users WHERE age >= ?",
18
);
// Single row by SQL
Row user = Db.selectOneBySql(
"SELECT * FROM users WHERE id = ?",
1L
);
// Select by primary key
Row pkRow = Row.ofKey(RowKey.of("id"), 1L);
Row selectedById = Db.selectOneById("users", pkRow);
// Select by single primary key
Row singlePkSelect = Db.selectOneById("users", "id", 1L);
// Schema-aware select
Row schemaSelect = Db.selectOneById("public", "users", "id", 1L);
// Select by Map conditions
Map<String, Object> selectConditions = Map.of(
"active", true,
"account_type", "premium"
);
List<Row> mapSelected = Db.selectListByMap("users", selectConditions);
// Select by Map with limit
List<Row> limitedMapSelect = Db.selectListByMap("users", selectConditions, 10L);
// Select by QueryCondition
QueryCondition condition = USER.AGE.between(25, 35).and(USER.ACTIVE.eq(true));
List<Row> conditionSelected = Db.selectListByCondition("users", condition);
// Select by QueryCondition with limit
List<Row> limitedCondition = Db.selectListByCondition("users", condition, 5L);
// Select by QueryWrapper
QueryWrapper selectQuery = QueryWrapper.create()
.select(USER.ID, USER.NAME, USER.EMAIL)
.from(USER)
.where(USER.ACTIVE.eq(true))
.orderBy(USER.CREATED_TIME.desc())
.limit(20);
List<Row> querySelected = Db.selectListByQuery("users", selectQuery);
// Select with QueryWrapper containing FROM clause
List<Row> fullQuerySelect = Db.selectListByQuery(selectQuery);
// Select all rows
List<Row> allUsers = Db.selectAll("users");
List<Row> allSchemaUsers = Db.selectAll("public", "users");
}
private List<Row> generateLargeDataSet() {
// Helper method for batch examples
List<Row> data = new ArrayList<>();
for (int i = 0; i < 5000; i++) {
data.add(Row.create()
.set("id", i)
.set("status", "pending")
.set("created_time", new Date()));
}
return data;
}
private String generateAccountNumber() {
return "ACC" + System.currentTimeMillis();
}Specialized selection methods for single values, object lists, and key-value mappings.
Object Selection Examples:
public void demonstrateObjectSelection() {
// Select single object (1 row, 1 column)
Long userCount = (Long) Db.selectObject(
"SELECT COUNT(*) FROM users WHERE active = ?",
true
);
// Select object by QueryWrapper
QueryWrapper countQuery = QueryWrapper.create()
.select(Functions.count())
.from(USER)
.where(USER.ACTIVE.eq(true));
Long countByQuery = (Long) Db.selectObject("users", countQuery);
// Select with schema
Long schemaCount = (Long) Db.selectObject("public", "users", countQuery);
// Select first and second columns as Map (key-value pairs)
Map<String, String> userNameEmailMap = Db.selectFirstAndSecondColumnsAsMap(
"SELECT name, email FROM users WHERE active = ?",
true
);
// Key-value mapping by QueryWrapper
QueryWrapper kvQuery = QueryWrapper.create()
.select(USER.NAME, USER.EMAIL)
.from(USER)
.where(USER.ACTIVE.eq(true));
Map<String, String> kvByQuery = Db.selectFirstAndSecondColumnsAsMap("users", kvQuery);
// Select multiple object values (multiple rows, 1 column)
List<Object> userIds = Db.selectObjectList(
"SELECT id FROM users WHERE active = ?",
true
);
// Object list by QueryWrapper
QueryWrapper listQuery = QueryWrapper.create()
.select(USER.ID)
.from(USER)
.where(USER.ACTIVE.eq(true));
List<Object> idsByQuery = Db.selectObjectList("users", listQuery);
// Schema-aware object selection
List<Object> schemaIds = Db.selectObjectList("public", "users", listQuery);
// Full query object selection
QueryWrapper fullListQuery = QueryWrapper.create()
.select(USER.EMAIL)
.from(USER)
.where(USER.ACTIVE.eq(true))
.orderBy(USER.CREATED_TIME.desc())
.limit(100);
List<Object> fullQueryIds = Db.selectObjectList(fullListQuery);
}### Count Operations and Statistics
Efficient counting and statistical operations with various condition types.
**Count Examples:**
```java
public void demonstrateCountOperations() {
// Raw SQL count
long totalUsers = Db.selectCount(
"SELECT COUNT(*) FROM users WHERE active = ?",
true
);
// Count by QueryCondition
QueryCondition ageCondition = USER.AGE.between(18, 65);
long adultCount = Db.selectCountByCondition("users", ageCondition);
// Schema-aware count
long schemaCount = Db.selectCountByCondition("public", "users", ageCondition);
// Count by QueryWrapper
QueryWrapper countQuery = QueryWrapper.create()
.from(USER)
.where(USER.ACTIVE.eq(true))
.and(USER.EMAIL_VERIFIED.eq(true));
long verifiedActiveCount = Db.selectCountByQuery("users", countQuery);
// Schema-aware QueryWrapper count
long schemaQueryCount = Db.selectCountByQuery("public", "users", countQuery);
// Count with QueryWrapper containing FROM clause
QueryWrapper fullCountQuery = QueryWrapper.create()
.select(Functions.count())
.from(USER)
.where(USER.REGISTRATION_DATE.ge(thisYear));
long fullQueryCount = Db.selectCountByQuery(fullCountQuery);
}Comprehensive pagination support with automatic count optimization and flexible configurations.
Pagination Examples:
public void demonstratePaginationOperations() {
// Basic pagination by QueryCondition
QueryCondition activeCondition = USER.ACTIVE.eq(true);
Page<Row> page1 = Db.paginate("users", 1, 20, activeCondition);
System.out.println("Page: " + page1.getPageNumber());
System.out.println("Size: " + page1.getPageSize());
System.out.println("Total: " + page1.getTotalRow());
System.out.println("Pages: " + page1.getTotalPage());
// Schema-aware pagination
Page<Row> schemaPage = Db.paginate("public", "users", 1, 20, activeCondition);
// Pagination with known total count (skips count query for performance)
long knownTotal = 1000L;
Page<Row> optimizedPage = Db.paginate("users", 2, 20, knownTotal, activeCondition);
// Pagination by QueryWrapper
QueryWrapper pageQuery = QueryWrapper.create()
.select(USER.ID, USER.NAME, USER.EMAIL, USER.CREATED_TIME)
.from(USER)
.where(USER.ACTIVE.eq(true))
.and(USER.EMAIL_VERIFIED.eq(true))
.orderBy(USER.CREATED_TIME.desc());
Page<Row> queryPage = Db.paginate("users", 1, 25, pageQuery);
// Schema-aware QueryWrapper pagination
Page<Row> schemaQueryPage = Db.paginate("public", "users", 1, 25, pageQuery);
// Pagination with QueryWrapper and known total
Page<Row> optimizedQueryPage = Db.paginate("users", 3, 25, 2500L, pageQuery);
// Advanced pagination using Page object
Page<Row> customPage = new Page<>(2, 30);
customPage.setTotalRow(5000L); // Set known total for optimization
Page<Row> advancedPage = Db.paginate("users", customPage, pageQuery);
// Schema-aware advanced pagination
Page<Row> schemaAdvancedPage = Db.paginate("public", "users", customPage, pageQuery);
// Process paginated results
for (Row user : queryPage.getRecords()) {
System.out.println("User: " + user.getString("name") +
", Email: " + user.getString("email"));
}
}### Advanced Batch Operations
Powerful batch processing utilities with generic mapper support and flexible execution patterns.
**Batch Execution Examples:**
```java
public void demonstrateBatchExecutionUtilities() {
// Generic batch execution with total size control
int totalOperations = 10000;
int batchSize = 500;
int[] results = Db.executeBatch(totalOperations, batchSize, RowMapper.class,
(mapper, index) -> {
// Execute operation for each index
Row data = Row.create()
.set("batch_id", index / batchSize)
.set("item_index", index)
.set("processed_time", new Date());
return mapper.insert(null, "batch_log", data);
});
// Batch execution with data collection
List<String> emailsToProcess = Arrays.asList(
"user1@example.com", "user2@example.com", "user3@example.com"
);
int[] emailResults = Db.executeBatch(emailsToProcess, RowMapper.class,
(mapper, email) -> {
Row emailLog = Row.create()
.set("email", email)
.set("status", "processed")
.set("processed_time", new Date());
return mapper.insert(null, "email_log", emailLog);
});
// Batch execution with data collection and batch size control
List<Row> dataToProcess = generateLargeDataSet();
int[] controlledResults = Db.executeBatch(dataToProcess, 1000, RowMapper.class,
(mapper, row) -> {
// Process each row
row.set("processed", true);
row.set("process_time", new Date());
return mapper.updateById(null, "processing_queue", row);
});
System.out.println("Processed " + controlledResults.length + " items");
}
// Custom batch arguments setter example
public void demonstrateCustomBatchUpdate() {
BatchArgsSetter batchSetter = new BatchArgsSetter() {
private final List<Object[]> batchArgs = Arrays.asList(
new Object[]{"active", new Date(), 1L},
new Object[]{"inactive", new Date(), 2L},
new Object[]{"pending", new Date(), 3L}
);
@Override
public int getBatchSize() {
return batchArgs.size();
}
@Override
public Object[] getSqlArgs(int index) {
return batchArgs.get(index);
}
};
int[] updateResults = Db.updateBatch(
"UPDATE users SET status = ?, last_updated = ? WHERE id = ?",
batchSetter
);
}Support for multiple datasources and environment-specific database operations.
Multi-Environment Examples:
public void demonstrateMultiEnvironmentOperations() {
// Get invoker for specific environment
RowMapperInvoker primaryInvoker = Db.invoker(); // Default environment
RowMapperInvoker analyticsInvoker = Db.invoker("analytics"); // Analytics DB
RowMapperInvoker reportingInvoker = Db.invoker("reporting"); // Reporting DB
// All Db methods work with default environment
// For specific environments, you would use the invokers directly
// or configure the FlexGlobalConfig appropriately
// Example of cross-environment data synchronization
List<Row> primaryData = Db.selectAll("users"); // From primary DB
// Process and insert into analytics environment
// (This would require using the specific invoker or environment configuration)
for (Row user : primaryData) {
Row analyticsRow = Row.create()
.set("user_id", user.get("id"))
.set("name", user.getString("name"))
.set("registration_date", user.getDate("created_time"))
.set("sync_time", new Date());
// Insert would use analytics environment configuration
// analyticsInvoker.insert(null, "user_analytics", analyticsRow);
}
}### Advanced Transaction Management
Comprehensive transaction support with propagation control and flexible execution patterns.
**Transaction API:**
```java { .api }
// Basic transaction operations
public static boolean tx(Supplier<Boolean> supplier);
public static boolean tx(Supplier<Boolean> supplier, Propagation propagation);
public static <T> T txWithResult(Supplier<T> supplier);
public static <T> T txWithResult(Supplier<T> supplier, Propagation propagation);
// Transaction propagation types
public enum Propagation {
REQUIRED, // Join existing or create new transaction
REQUIRES_NEW, // Always create new transaction
SUPPORTS, // Join existing, no transaction if none exists
NOT_SUPPORTED, // Execute without transaction
NEVER, // Throw exception if transaction exists
MANDATORY // Throw exception if no transaction exists
}Advanced Transaction Examples:
public void demonstrateAdvancedTransactions() {
// Basic transaction with boolean result (rollback on false/null or exception)
boolean success = Db.tx(() -> {
// Complex business logic
Row newUser = Row.create()
.set("name", "Transaction User")
.set("email", "tx.user@example.com")
.set("balance", 1000.00);
int userInserted = Db.insert("users", newUser);
// Create account
Row account = Row.create()
.set("user_id", newUser.get("id"))
.set("account_number", generateAccountNumber())
.set("balance", 1000.00)
.set("status", "active");
int accountInserted = Db.insert("accounts", account);
// Log transaction
Row transactionLog = Row.create()
.set("action", "account_creation")
.set("user_id", newUser.get("id"))
.set("amount", 1000.00)
.set("timestamp", new Date());
int logInserted = Db.insert("transaction_log", transactionLog);
// Return false to rollback, true to commit
return userInserted > 0 && accountInserted > 0 && logInserted > 0;
});
// Transaction with result (only rollback on exception)
String processResult = Db.txWithResult(() -> {
// Process payments
List<Row> pendingPayments = Db.selectListByMap("payments",
Map.of("status", "pending"));
int processedCount = 0;
for (Row payment : pendingPayments) {
// Update payment status
Row updateData = Row.create().set("status", "processed");
Map<String, Object> whereCondition = Map.of("id", payment.get("id"));
int updated = Db.updateByMap("payments", updateData, whereCondition);
if (updated > 0) {
processedCount++;
}
}
return "Processed " + processedCount + " payments";
});
// Transaction with propagation control
boolean nestedResult = Db.tx(() -> {
// Outer transaction
Row outerData = Row.create().set("level", "outer").set("timestamp", new Date());
Db.insert("transaction_test", outerData);
// Inner transaction with REQUIRES_NEW (creates separate transaction)
String innerResult = Db.txWithResult(() -> {
Row innerData = Row.create().set("level", "inner").set("timestamp", new Date());
Db.insert("transaction_test", innerData);
return "Inner transaction completed";
}, Propagation.REQUIRES_NEW);
// This will commit/rollback independently of inner transaction
return innerResult != null;
}, Propagation.REQUIRED);
// Complex transaction with error handling
try {
boolean complexResult = Db.tx(() -> {
// Multiple related operations
// 1. Create order
Row order = Row.create()
.set("customer_id", 123L)
.set("total_amount", 299.99)
.set("status", "pending")
.set("created_time", new Date());
int orderCreated = Db.insert("orders", order);
// 2. Update inventory
Row inventoryUpdate = Row.create().set("quantity",
Functions.subtract(INVENTORY.QUANTITY, 1));
int inventoryUpdated = Db.updateByMap("inventory", inventoryUpdate,
Map.of("product_id", 456L));
// 3. Create payment record
Row payment = Row.create()
.set("order_id", order.get("id"))
.set("amount", 299.99)
.set("payment_method", "credit_card")
.set("status", "pending");
int paymentCreated = Db.insert("payments", payment);
// All operations must succeed
return orderCreated > 0 && inventoryUpdated > 0 && paymentCreated > 0;
});
if (complexResult) {
System.out.println("Order processing completed successfully");
} else {
System.out.println("Order processing failed and was rolled back");
}
} catch (Exception e) {
System.err.println("Transaction failed with exception: " + e.getMessage());
// Transaction was automatically rolled back
}
}## Types and Supporting Classes
```java { .api }
// Core Row operations
public class Row extends LinkedHashMap<String, Object> {
public static Row ofMap(Map<String, Object> map);
public static Row ofKey(RowKey rowKey, Object value);
public static Row create();
public Row set(String column, Object value);
public <T> T get(String column, Class<T> clazz);
public String getString(String column);
public Integer getInt(String column);
public Long getLong(String column);
public Boolean getBoolean(String column);
public Date getDate(String column);
}
// Primary key support
public class RowKey {
public static RowKey of(String keyColumn);
public static RowKey of(String... keyColumns);
}
// Pagination support
public class Page<T> {
public Page(Number pageNumber, Number pageSize);
public Page(Number pageNumber, Number pageSize, Number totalRow);
public int getPageNumber();
public int getPageSize();
public long getTotalRow();
public int getTotalPage();
public List<T> getRecords();
public void setTotalRow(long totalRow);
}
// Query building
public class QueryWrapper {
public static QueryWrapper create();
public QueryWrapper select(QueryColumn... columns);
public QueryWrapper from(QueryTable table);
public QueryWrapper where(QueryCondition condition);
public QueryWrapper where(Map<String, Object> whereColumns);
public QueryWrapper and(QueryCondition condition);
public QueryWrapper orderBy(QueryColumn column);
public QueryWrapper limit(Long limit);
}
// Query conditions
public class QueryCondition {
// Created through QueryColumn methods
}
// Batch processing
public interface BatchArgsSetter {
int getBatchSize();
Object[] getSqlArgs(int index);
}
// Transaction propagation
public enum Propagation {
REQUIRED, REQUIRES_NEW, SUPPORTS, NOT_SUPPORTED, NEVER, MANDATORY
}
// Multi-environment support
public class RowMapperInvoker {
// Used for environment-specific operations
// Accessible via Db.invoker() and Db.invoker(environmentId)
}
// Functional interfaces
@FunctionalInterface
public interface Supplier<T> {
T get();
}
@FunctionalInterface
public interface BiConsumer<T, U> {
void accept(T t, U u);
}
// Standard Java collections
public interface Collection<E> {
int size();
boolean isEmpty();
Iterator<E> iterator();
}
public interface List<E> extends Collection<E> {
E get(int index);
int size();
boolean isEmpty();
}
public interface Map<K, V> {
V get(Object key);
V put(K key, V value);
Set<K> keySet();
Collection<V> values();
}Install with Tessl CLI
npx tessl i tessl/maven-com-mybatis-flex--mybatis-flex-core