Skip to content

SQL Injector

MyBatis-Plus provides a flexible mechanism for injecting custom SQL methods 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 meet specific business logic and query requirements. Here are some example use cases and functionalities of the SQL injector:

Use Cases

  1. Custom Query Methods: When standard CRUD operations cannot meet complex query requirements, custom query methods can be added via the SQL injector.

  2. Complex Data Processing: For scenarios requiring complex data processing, such as multi-table joins, subqueries, or aggregate functions, the SQL injector can help generate the corresponding SQL statements.

  3. Performance Optimization: Custom SQL statements can be used to optimize performance for specific query scenarios.

  4. Data Permission Control: When SQL statements need to be dynamically generated based on user permissions, the SQL injector can help implement data permission control.

  5. Legacy System Migration: When migrating legacy systems to MyBatis-Plus, preserving the original SQL statement structure may be necessary, and the SQL injector can facilitate this transition.

Functionalities

  1. Inject Custom SQL Methods: By implementing the ISqlInjector interface, custom SQL methods can be injected into the MyBatis container, including any complex SQL queries.

  2. Extend BaseMapper: Additional query methods can be added to BaseMapper via the SQL injector, and these methods will be automatically recognized and used by MyBatis-Plus.

  3. Flexible SQL Generation: The SQL injector provides a flexible SQL generation mechanism to produce various SQL statements, including but not limited to SELECT, INSERT, UPDATE, and DELETE.

  4. Integrate Third-Party Database Features: For scenarios requiring specific database features like stored procedures or triggers, the SQL injector can generate SQL statements to invoke these functionalities.

  5. Dynamic SQL Support: In cases 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 offers 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.

ISqlInjector.java
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 sqlInjector.

Based on the provided reference information, we can see how to implement custom global methods in MyBatis-Plus, including logical deletion, auto-fill, and custom insert and insertBatch methods. Here is a more detailed step-by-step guide with example code:

Custom Global Method Guide

Step 1: Define SQL

First, define the SQL statements for your custom methods. This is typically done in 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, 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, define your 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, 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

Notes

  • When defining custom methods, ensure the method names match the IDs in the injected SQL statements.
  • When using custom batch insert and auto-fill features, ensure the @Param annotation is used on 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 execute the desired operations.

By following these steps, you can successfully implement custom global methods in MyBatis-Plus. Adjust the SQL statements and method implementations as needed for your specific business requirements.

More Examples

Refer to the Custom BaseMapper Example for detailed steps on creating custom SQL injectors and using them in your projects.

This approach allows MyBatis-Plus to extend its functionality to meet specific business needs while maintaining clean and maintainable code.

Baomidou

© 2016-2025 Baomidou™. All Rights Reserved.

Power by Astro Starlight | Sponsored by JetBrains

渝ICP备2021000141号-1 | 渝公网安备50011302222097