多条件查询--@Select注解里的动态sql语句

时间:2025-05-07 14:16:06

@Select注解

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Select
{
    String[] value();
}

从@Select注解源码中可以得到:
①@Select注解只能修饰方法
②@Select注解的值是字符串数组
所以,@Select注解的用法是:

@Select("Select * from Stu where id = #{id}")
Student selectById(String id);

@Select注解动态SQL拼写

@Select注解里普通的字符串只能实现变量替换的功能,若要实现复杂的逻辑判断,则要使用标签。例如:实现多条件查询即在网页进行搜索时,可以输入条件1进行搜索,也输入进行条件2进行搜索,并不能确定每次搜索输入的条件,此时可以使用标签进行判断:

@Select("<script> Select * from Stu "+
		"<if test='id != null and id !=\"\"'> and id = #{id} </if>" +
		"<if test='name != null and name !=\"\"'> and name = #{name} </if>" +
		"</script>")
Student selectById(String id, String name);

标签不是@Select注解专用的,其他的注解也可以使用,例如:@Insert、@Updata。