Springboot2註解使用Mybatis動態SQL
阿新 • • 發佈:2018-12-29
1、簡單SQL使用
//從***資料表獲取統計資料 @Select("select count(*) from issues where issue_type = #{type}") String getIssueCount(String type);
2、動態SQL使用
//獲取時間段內issue詳細資訊(可根據專案名、開發者名、問題型別獲取) @Select({"<script>", "select id,committername,type,count,projectname,file,line,message,creationdate,updatedate from issue","where creationdate BETWEEN #{startDate} AND #{endDate}", "<if test='committer != null and committer.length > 0'>", "AND committername IN", "<foreach item='item' index='index' collection='committer' open='(' close=')' separator=','>","#{item}", "</foreach>", "</if>", "<if test='type != null and type.length > 0'>", "AND type IN", "<foreach item='item' index='index' collection='type' open='(' close=')' separator=','>", "#{item}","</foreach>", "</if>", "<if test='project != null and project.length > 0'>", "AND projectname IN", "<foreach item='item' index='index' collection='project' open='(' close=')' separator=','>", "#{item}", "</foreach>", "</if>", "</script>"}) List<IssueModel> getDetailIssue(@Param("startDate") String startDate, @Param("endDate")String endDate, @Param("committer") String[] committer, @Param("type") String[] type, @Param("project") String[] project);
知識點:
(1)註解寫動態SQL,用<script>標籤包圍,然後像xml語法一樣書寫。
(2)SQL的拼接可以使用+號,也可以使用逗號。我這裡使用的是逗號,要使用+號可以把<script>前後的大括號去掉。
(2)實現IN查詢中 > 符號需要轉義為 > ,其中foreach的collection直接寫成@param中的值即可。
(3)這是一種使用註解完全替代XML的方法,稍微複雜的SQL語句推薦使用XML方式。