Springboot2註解使用Mybatis動態SQL

一、簡單SQL使用spa

//從***數據表獲取統計數據
    @Select("select count(*) from issues where issue_type = #{type}")
    String getIssueCount(String type);

二、動態SQL使用code

//獲取時間段內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 &gt; 0'>",
            "AND committername IN",
            "<foreach item='item' index='index' collection='committer' open='(' close=')' separator=','>",
            "#{item}",
            "</foreach>",
            "</if>",
            "<if test='type != null and type.length &gt; 0'>",
            "AND type IN",
            "<foreach item='item' index='index' collection='type' open='(' close=')' separator=','>",
            "#{item}",
            "</foreach>",
            "</if>",
            "<if test='project != null and project.length &gt; 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);

知識點:xml

(1)註解寫動態SQL,用<script>標籤包圍,而後像xml語法同樣書寫。blog

(2)SQL的拼接能夠使用+號,也能夠使用逗號。我這裏使用的是逗號,要使用+號能夠把<script>先後的大括號去掉。ip

(2)實現IN查詢中 > 符號須要轉義爲 &gt; ,其中foreach的collection直接寫成@param中的值便可。開發

(3)這是一種使用註解徹底替代XML的方法,稍微複雜的SQL語句推薦使用XML方式。get

相關文章
相關標籤/搜索