mybatis动态sql(注解方式)

就记录个实例,以后可以参考= =

方法一:provider

public class ArticleProvider {

    public String selectAll(Map<String, Object> map) {
        return new SQL() {{
            SELECT("sz_article.*,sz_article_category.name");
            FROM("sz_article");
            LEFT_OUTER_JOIN("sz_article_category on sz_article.category_id = sz_article_category.id");
            if (map.get("categoryId") != null) {
                WHERE("category_id = #{categoryId}");
            }
            if (StringUtils.isNotEmpty((String) map.get("key"))) {
                WHERE("title like CONCAT('%',#{key},'%')");
            }
        }}.toString();
    }
}

mapper

    @SelectProvider(type = ArticleProvider.class,method = "selectAll")
    @Results(@Result(property = "category.name",column = "name"))
    List<Article> selectAllWithCategory(Long categoryId,String key);

一些参考资料:

https://mybatis.org/mybatis-3/zh/statement-builders.html

https://blog.csdn.net/owen_william/article/details/51815506

方法二:使用if标签

需要配合script标签使用

    @Select("<script>select sz_article.*,sz_article_category.name from sz_article left join sz_article_category on sz_article.category_id=sz_article_category.id where 1=1 <if test='categoryId!=null'>and category_id=#{categoryId}</if> <if test='key!=null'>and title like CONCAT('%',#{key},'%')</if></script>")
    @Results(@Result(property = "category.name", column = "name"))
    List<Article> selectAllWithCategory(Long categoryId, String key);
  点赞

发表评论

电子邮件地址不会被公开。 必填项已用*标注