使用MyBatis很長時間了,一直使用的是XML配置的 SQL,剛好在上一個項目中嘗試使用注解方式開發,主要是由於XML配置過於繁瑣,注解可以直接寫在Mapper函數上,更加的方便一些。
在注解上不能直接使用動態的SQL,需要在其前后加入 <script>
@Select("<script> " + "SELECT id, name, email,password " + "FROM user " + " <where> " + " <if test=\"email != null\">id=#{email}</if> " + " <if test=\"name != null\"> AND name=#{name}</if> " + " </where> " + " </script> ")
否則MyBatis會報錯。
同時 對於LIKE 也是不能夠直接使用的 可以借助concat函數實現
@Select("SELECT name from user WHERE email LIKE concat(#{prefix},'%') limit 5")