SQL里面经常会遇到需要IN类型的搜索,如select * from table where id in (a, b, c)。
在Spring JPA里面直接传List的参数则会自动转换,但我在MyBatis里面好像没有成功,需要在注解里写一长串代码进行转换,太麻烦了!所以找了相关资料增强了注解,特此记录一下。
LanguageDriver
import org.apache.ibatis.mapping.SqlSource
import org.apache.ibatis.scripting.LanguageDriver
import org.apache.ibatis.scripting.xmltags.XMLLanguageDriver
import org.apache.ibatis.session.Configuration
import java.util.regex.Pattern
/**
* @Author: anson
* @Date: 2020/8/22 11:59 AM
*/
class SelectInLangDriver : XMLLanguageDriver(), LanguageDriver {
private val inPattern: Pattern = Pattern.compile("\\(#\\{(\\w+)\\}\\)")
override fun createSqlSource(configuration: Configuration,
script: String, parameterType: Class<*>): SqlSource {
val matcher = inPattern.matcher(script)
val newScript = if (matcher.find()) {
matcher.replaceAll("(<foreach collection=\"$1\" item=\"__item\" separator=\",\" >#{__item}</foreach>)")
} else script
return super.createSqlSource(configuration, "<script>$newScript</script>", parameterType)
}
}
使用方法如下
@Lang(SelectInLangDriver::class)
@Select("SELECT * FROM any WHERE id in (#{ids})")
fun findByIds(@Param("ids") docIds: List<String>): List<Any>
[1] Refenence
网友评论