从3.2版本开始,MyBatis支持可插拔的脚本语言,因此您可以插入一个语言驱动程序,并使用该语言来编写动态SQL查询。
您可以通过实现以下接口来插入一种语言:
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);
}
一旦您有了自定义的语言驱动程序,可以通过在mybatis-config.xml文件中进行配置将其设置为默认值:
<typeAliases>
<typeAlias type="org.sample.MyLanguageDriver" alias="myLanguage"/>
</typeAliases>
<settings>
<setting name="defaultScriptingLanguage" value="myLanguage"/>
</settings>
您可以通过添加以下方式的lang属性来为特定的语句指定语言,而无需更改默认配置:
<select id="selectBlog" lang="myLanguage">
SELECT * FROM BLOG
</select>
或者,如果您正在使用映射器,则可以使用`@Lang`注解:
public interface Mapper {
@Lang(MyLanguageDriver.class)
@Select("SELECT * FROM BLOG")
List<Blog> selectBlog();
}
注意:您可以使用Apache Velocity作为您的动态语言。详细信息请参阅MyBatis-Velocity项目。
在前面的部分中介绍的所有XML标签都是由默认的MyBatis语言提供的,该语言由驱动程序 org.apache.ibatis.scripting.xmltags.XmlLanguageDriver
提供,其别名为xml。