mybatis自带的解析已经蛮强大,至少我们能够用mybatis简单的语法来表达我们sql拼接时候的语义,比如$、#等诸如此类的符号意思,但是其实你并不喜欢再重新去理解一套它的语法,比如贵公司有自定义的一套组件,也许*代表的意思就是占位符,如果是这样的话,mybatis提供一套语法语义的解析的接口,只需要你注册进去,那么就按照你的想法进行解析。
首先我们查看UML图,来查阅下现阶段的mybatis是解析工作
上述几个类大致是用来解析的关键类,除了EwellPlugin的插件类是自定义以外,就能完成你自定义的解析组件开发,代码其实蛮简单的,这里是关于velocity的模板引擎的自定义组件放入mybatis的解析池中。其实对于mybatis访问DB最为重要的解析语句和绑定参数都在BoundSql类中,其实任何ORM framework最终的访问DB其实就是JDBC一样的,因为这些已经成为标准化,反过来数据库的驱动其实还是挺不一样的。
public class EwellDriver implements LanguageDriver {
@Override
public ParameterHandler createParameterHandler(MappedStatement mappedStatement, Object parameterObject, BoundSql boundSql) {
return new DefaultParameterHandler(mappedStatement, parameterObject, boundSql);
}
@Override
public SqlSource createSqlSource(Configuration configuration, XNode script, Class<?> parameterTypeClass) {
if (parameterTypeClass == null) {
parameterTypeClass = Object.class;
}
return new SQLScriptSource(configuration, script.getNode().getTextContent(), parameterTypeClass);
}
@Override
public SqlSource createSqlSource(Configuration configuration, String script, Class<?> parameterTypeClass) {
if (parameterTypeClass == null) {
parameterTypeClass = Object.class;
}
return new SQLScriptSource(configuration, script, parameterTypeClass);
}
}
public class SQLScriptSource implements SqlSource {
protected static final String PARAMETER_OBJECT_KEY = "_parameter";
protected static final String DATABASE_ID_KEY = "_databaseId";
protected static final String MAPPING_COLLECTOR_KEY = "_pmc";
protected static final String VARIABLES_KEY = "_vars";
private static int templateIndex = 0;
private final ParameterMapping[] parameterMappingSources;
private final Object compiledScript;
private final Configuration configuration;
public SQLScriptSource(Configuration configuration, String script, Class<?> parameterTypeClass) {
this.configuration = configuration;
ParameterMappingSourceParser mappingParser = new ParameterMappingSourceParser(configuration, script, parameterTypeClass);
parameterMappingSources = mappingParser.getParameterMappingSources();
script = mappingParser.getSql();
compiledScript = VelocityFacade.compile(script, "velocity-template-" + (++templateIndex));
}
@Override
public BoundSql getBoundSql(Object parameterObject) {
final Map<String, Object> context = new HashMap<String, Object>();
final ParameterMappingCollector pmc = new ParameterMappingCollector(parameterMappingSources, context, configuration);
context.put(DATABASE_ID_KEY, configuration.getDatabaseId());
context.put(PARAMETER_OBJECT_KEY, parameterObject);
context.put(MAPPING_COLLECTOR_KEY, pmc);
context.put(VARIABLES_KEY, configuration.getVariables());
final String sql = VelocityFacade.apply(compiledScript, context);
BoundSql boundSql = new BoundSql(configuration, sql, pmc.getParameterMappings(), parameterObject);
for (Map.Entry<String, Object> entry : context.entrySet()) {
boundSql.setAdditionalParameter(entry.getKey(), entry.getValue());
}
return boundSql;
}
}