mybatis 查询Select 用对象传递参数到 when test筛选
在MyBatis中,可以使用对象来传递参数,并在@Select注解中使用when test来筛选查询条件。
首先,定义一个包含查询条件的对象,例如:
public class QueryParam {
private String name;
private Integer age;
// 省略getter和setter方法
}
然后,在Mapper接口中定义一个使用@Select注解的查询方法,如下所示:
@Mapper
public interface UserMapper {
@Select("SELECT * FROM user WHERE 1=1" +
"<when test='name != null'> AND name = #{name}</when>" +
"<when test='age != null'> AND age = #{age}</when>")
List<User> getUsers(QueryParam param);
}
在@Select注解中使用
最后,在使用该查询方法时,可以直接传递一个QueryParam对象作为参数,MyBatis会根据对象的属性值进行查询。例如:
@Autowired
private UserMapper userMapper;
public List<User> getUsers(String name, Integer age) {
QueryParam param = new QueryParam();
param.setName(name);
param.setAge(age);
return userMapper.getUsers(param);
}
在调用getUsers方法时,可以传递name和age参数,MyBatis会根据这些参数值进行查询。如果某个参数为null,则不会作为查询条件
原文地址: http://www.cveoy.top/t/topic/hJmY 著作权归作者所有。请勿转载和采集!