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

相关文章
相关标签/搜索