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:

  1. public interface LanguageDriver {
  2. ParameterHandler createParameterHandler(MappedStatement mappedStatement, Object parameterObject, BoundSql boundSql);
  3. SqlSource createSqlSource(Configuration configuration, XNode script, Class<?> parameterType);
  4. SqlSource createSqlSource(Configuration configuration, String script, Class<?> parameterType);
  5. }

Once you have your custom language driver you can set it to be the default by configuring it in the mybatis-config.xml file:

  1. <typeAliases>
  2. <typeAlias type="org.sample.MyLanguageDriver" alias="myLanguage"/>
  3. </typeAliases>
  4. <settings>
  5. <setting name="defaultScriptingLanguage" value="myLanguage"/>
  6. </settings>

Instead of changing the default, you can specify the language for an specific statement by adding the lang attribute as follows:

  1. <select id="selectBlog" lang="myLanguage">
  2. SELECT * FROM BLOG
  3. </select>

Or, in the case you are using mappers, using the @Lang annotation:

  1. public interface Mapper {
  2. @Lang(MyLanguageDriver.class)
  3. @Select("SELECT * FROM BLOG")
  4. List<Blog> selectBlog();
  5. }

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.