SQL Injector
MyBatis-Plus provides a flexible mechanism for injecting custom SQL methods, achieved through the global sqlInjector
configuration. By implementing the ISqlInjector
interface or extending the AbstractSqlInjector
abstract class, you can inject custom generic methods into the MyBatis container.
The SQL Injector allows developers to extend and customize SQL statement generation to accommodate specific business logic and query requirements. Here are some example usage scenarios and the capabilities it enables:
Usage Scenarios
-
Custom Query Methods: When standard CRUD operations are insufficient for complex query needs, you can add custom query methods via the SQL Injector.
-
Complex Data Processing: For scenarios requiring complex data processing, such as multi-table joins, subqueries, and aggregate functions, the SQL Injector can help generate the corresponding SQL statements.
-
Performance Optimization: Custom SQL statements allow for performance optimization tailored to specific query scenarios.
-
Data Permission Control: When SQL statements need to be dynamically generated based on user permissions, the SQL Injector can be used to implement data permission control.
-
Legacy System Migration: When migrating legacy systems to MyBatis-Plus, you may need to preserve the original SQL statement structure. The SQL Injector can facilitate this transition.
Capabilities
-
Inject Custom SQL Methods: By implementing the
ISqlInjector
interface, you can inject custom SQL methods into the MyBatis container. These methods can represent any complex SQL query. -
Extend BaseMapper: You can add additional query methods by extending
BaseMapper
through the SQL Injector. These methods will be automatically recognized and used by MyBatis-Plus. -
Flexible SQL Generation: The SQL Injector provides a flexible SQL generation mechanism, allowing the creation of various SQL statements (SELECT, INSERT, UPDATE, DELETE, etc.) based on business requirements.
-
Integrate Third-Party Database Features: If you need to use specific database features like stored procedures or triggers, the SQL Injector can help generate SQL statements that invoke these features.
-
Dynamic SQL Support: In scenarios where SQL statements need to be dynamically generated based on runtime conditions, the SQL Injector supports this dynamic SQL generation.
Through the SQL Injector, MyBatis-Plus provides a powerful extension point, enabling developers to flexibly customize and optimize SQL statements according to project-specific needs, thereby improving application performance and adaptability.
Injector Configuration
In MyBatis-Plus, the sqlInjector
configuration is a global setting used to specify a class that implements the ISqlInjector
interface. This class is responsible for injecting custom SQL methods into MyBatis Mapper interfaces.
public interface ISqlInjector {
/** * Check if SQL has already been injected (skip if already injected) * * @param builderAssistant mapper builder assistant * @param mapperClass mapper interface class object */ void inspectInject(MapperBuilderAssistant builderAssistant, Class<?> mapperClass);}
The default injector implementation is DefaultSqlInjector. You can refer to it when creating your own injector.
Below is an example of how to configure the sqlInjector
.
Based on the provided reference information, we can see how to implement custom global methods in MyBatis-Plus, including logical delete, automatic filling, and custom insert
and insertBatch
methods. Here is a more detailed step-by-step guide and example code:
Custom Global Methods Guide
Step 1: Define the SQL
First, you need to define the SQL statements for your custom methods. This is typically done within a class that extends AbstractMethod
, such as MysqlInsertAllBatch
.
public class MysqlInsertAllBatch extends AbstractMethod {
/** * @since 3.5.0 */ public MysqlInsertAllBatch() { super("mysqlInsertAllBatch"); }
@Override public MappedStatement injectMappedStatement(Class<?> mapperClass, Class<?> modelClass, TableInfo tableInfo) { // Define SQL statement (primary key + regular fields) insert into table(....) values(....),(....) String sql = "INSERT INTO " + tableInfo.getTableName() + "(" + tableInfo.getKeyColumn() + "," + tableInfo.getFieldList().stream().map(TableFieldInfo::getColumn).collect(Collectors.joining(",")) + ") VALUES "; String value = "(" + "#{" + ENTITY + DOT + tableInfo.getKeyProperty() + "}" + "," + tableInfo.getFieldList().stream().map(tableFieldInfo -> "#{" + ENTITY + DOT + tableFieldInfo.getProperty() + "}") .collect(Collectors.joining(",")) + ")"; String valuesScript = SqlScriptUtils.convertForeach(value, "list", null, ENTITY, COMMA); SqlSource sqlSource = super.createSqlSource(configuration, "<script>" + sql + valuesScript + "</script>", modelClass); KeyGenerator keyGenerator = tableInfo.getIdType() == IdType.AUTO ? Jdbc3KeyGenerator.INSTANCE : NoKeyGenerator.INSTANCE; // The third parameter must match the custom method name in baseMapper return this.addInsertMappedStatement(mapperClass, modelClass, this.methodName, sqlSource, keyGenerator,tableInfo.getKeyProperty(), tableInfo.getKeyColumn()); }}
Step 2: Register Custom Methods
Next, you need to create a class that extends DefaultSqlInjector
and override the getMethodList
method to register your custom methods.
public class MyLogicSqlInjector extends DefaultSqlInjector {
@Override public List<AbstractMethod> getMethodList(Class<?> mapperClass) { List<AbstractMethod> methodList = super.getMethodList(mapperClass); methodList.add(new DeleteAll()); methodList.add(new MyInsertAll()); methodList.add(new MysqlInsertAllBatch()); return methodList; }}
Step 3: Define BaseMapper
Then, you need to define the custom methods in your BaseMapper interface.
public interface MyBaseMapper<T> extends BaseMapper<T> {
Integer deleteAll();
int myInsertAll(T entity);
int mysqlInsertAllBatch(@Param("list") List<T> batchList);}
Step 4: Configure SqlInjector
Finally, you need to specify your custom SQL injector in the configuration file.
Configure in application.yml
mybatis-plus: global-config: sql-injector: com.example.MyLogicSqlInjector
Configure in application.properties
mybatis-plus.global-config.sql-injector=com.example.MyLogicSqlInjector
Important Notes
- When defining custom methods, ensure the method name matches the ID used in the injected SQL statement.
- When using custom batch insert and automatic fill functionality, ensure you use the
@Param
annotation on the Mapper method parameters, and the naming conforms to MyBatis-Plus’s default support (list
,collection
,array
). - Custom SQL statements should be written according to your business requirements to ensure they correctly perform the intended operations.
By following these steps, you can successfully implement custom global methods in MyBatis-Plus. Remember to adjust the SQL statements and method implementations according to your specific business needs in practice.
More Examples
Refer to the Custom BaseMapper Example for detailed steps on how to create custom SQL injectors and use them in your projects.
This approach allows MyBatis-Plus to extend its functionality to meet specific business requirements while maintaining clean and maintainable code.