Mybatis注解方式实现sql动态语句

Mybatis注解方式实现sql动态语句

如果要使用注解的方式来实现动态查询就要注解里加入<script></Script>标签,然后在此标签中来实现动态的sql语句
如:

@Select({"<script>"
            +"select * from Student where 1=1"
            +"<if test='name!=null'>and name like concat('%',#{name},'%')</if>"
            +"<if test='qq!=null'>and qq like concat('%',#{qq},'%')</if>"
            +"</script>"})

1.单使用if标签

@Select({
    
    "<script>"
            +"select * from Student where 1=1"
            +"<if test='name!=null'>and name like concat('%',#{name},'%')</if>"
            +"<if test='qq!=null'>and qq like concat('%',#{qq},'%')</if>"
            +"</script>"})
    List<Student> select_by_nameAndQq(Student student);

2.使用if和where标签

使用where标签就不需要在sql语句的后面加上1=1再接and语句,由where标签来动态判断是否要接and

@Select({
    
    "<script>"
            +"select * from Student"
            +"<where>"
            +"<if test='name!=null'>and name like concat('%',#{name},'%')</if>"
            +"<if test='qq!=null'>and qq like concat('%',#{qq},'%')</if>"
            +"</where>"
            +"</script>"})
    List<Student> select_by_nameAndQq_where(Student student);

3.注解实现动态sql语句的符号问题

使用注解的方式来实现动态sql语句是不能使用">""<"之类的符号,如果要使用只能使用转义字符的方式来使用
在这里插入图片描述

@Select({
    
    "<script>"
            +"select * from Student"
            +"<where>"
            +"<if test='name!=null'>and name like concat('%',#{name},'%')</if>"
            +"<if test='ageS &gt; 0 and ageE &gt; 0'>and age between #{ageS} and #{ageE}</if>"
            +"</where>"
            +"</script>"})
    List<Student> select_by_nameAndAge(Map<String,Object> map);

注意:这里接口里的方法使用的参数是泛型集合或者JavaBean对象时,一定要将里面的键值和注解里的名字对应。

猜你喜欢

转载自blog.csdn.net/Jackbillzsc/article/details/109014795