Pluggable Scripting Languages For Dynamic SQL
Starting from version 3.2 MyBatis supports pluggable scripting languages, so you can plug a language driver and use that language to write your dynamic SQL queries.
You can plug a language by implementing the following interface:
public interface LanguageDriver {
ParameterHandler createParameterHandler(MappedStatement mappedStatement, Object parameterObject, BoundSql boundSql);
SqlSource createSqlSource(Configuration configuration, XNode script, Class<?> parameterType);
SqlSource createSqlSource(Configuration configuration, String script, Class<?> parameterType);
}
Once you have your custom language driver you can set it to be the default by configuring it in the mybatis-config.xml file:
<typeAliases>
<typeAlias type="org.sample.MyLanguageDriver" alias="myLanguage"/>
</typeAliases>
<settings>
<setting name="defaultScriptingLanguage" value="myLanguage"/>
</settings>
Instead of changing the default, you can specify the language for an specific statement by adding the lang
attribute as follows:
<select id="selectBlog" lang="myLanguage">
SELECT * FROM BLOG
</select>
Or, in the case you are using mappers, using the @Lang
annotation:
public interface Mapper {
@Lang(MyLanguageDriver.class)
@Select("SELECT * FROM BLOG")
List<Blog> selectBlog();
}
NOTE You can use Apache Velocity as your dynamic language. Have a look at the MyBatis-Velocity project for the details.
All the xml tags you have seen in the previous sections are provided by the default MyBatis language that is provided by the driver org.apache.ibatis.scripting.xmltags.XmlLanguageDriver
which is aliased as xml
.