Hint
This article is generated by AI translation.
Custom Rules
When dbVisitor built-in rules cannot meet your needs, you can extend with custom rules by implementing the SqlRule interface.
Implementation Steps
1. Implement the SqlRule interface
import net.hasor.dbvisitor.dynamic.QueryContext;
import net.hasor.dbvisitor.dynamic.SqlArgSource;
import net.hasor.dbvisitor.dynamic.SqlBuilder;
import net.hasor.dbvisitor.dynamic.rule.SqlRule;
import net.hasor.dbvisitor.internal.OgnlUtils;
import net.hasor.cobble.StringUtils;
public class MyRule implements SqlRule {
@Override
public boolean test(SqlArgSource data, QueryContext context, String activeExpr) {
// activeExpr is the "activation condition" in @{ruleName, activation condition, rule content}
// Return true to indicate the rule should execute
return StringUtils.isBlank(activeExpr) || Boolean.TRUE.equals(OgnlUtils.evalOgnl(activeExpr, data));
}
@Override
public void executeRule(SqlArgSource data, QueryContext context,
SqlBuilder sqlBuilder, String activeExpr, String ruleValue) {
// ruleValue is the "rule content" in @{ruleName, activation condition, rule content}
// Use sqlBuilder to assemble the generated SQL fragment
sqlBuilder.appendSql("my_custom_value");
}
}
2. Register the rule (choose one)
// Method 1: Register via Configuration (recommended)
Configuration config = new Configuration();
config.addSqlRule("myrule", new MyRule());
// Method 2: Register to the global default registry
RuleRegistry.DEFAULT.register("myrule", new MyRule());
3. Use the rule
select * from users where id = @{myrule, true, xxxx}
Interface Description
The SqlRule interface defines two methods:
| Method | Description |
|---|---|
test(data, context, activeExpr) | Determines whether the rule should execute. If false, the entire @{...} is skipped. |
executeRule(data, context, sqlBuilder, activeExpr, ruleValue) | Executes the rule logic, assembling SQL fragments and arguments via sqlBuilder. |
Argument parsing rule: In @{ruleName, activeExpr, ruleValue}, content before the first comma is the rule name, content before the second comma is activeExpr, and everything after is ruleValue.
Hint
Rule names are case-insensitive. A rule registered as "myrule" can be invoked via @{MyRule}, @{MYRULE}, etc.