代码语言:txt复制
@Data
public class SearchServerDto implements Serializable {
private Long serverid;
private String host;
private String nickname;
private Date createtime;
}
若前端传入该对象,想通过该对象进行搜索按条件搜索
如果采用传统的方法,进行每一个属性都进行判断则需要很多的if else if
但如果采用反射和注解的思想将减少繁琐的步骤,且具有通用性
分析:
作者使用的是Mybatis-X生成的实体类
有注解@TableId、@TableField,故新添了一个注解来做分辨
代码语言:txt复制@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface FieldAnnoation {
String Annoationtype() default "TableField";
}
可以使用反射,动态的将SearchServerDto注入到QueryWrapper 中
代码语言:txt复制
QueryWrapper<UserServer> queryWrapper = new QueryWrapper<>();
UserServer userServer = new UserServer();
List<UserServer> list;
if (ObjectUtils.isEmpty(searchServerDto)){
list = userServerService.list();
}else{
Class<? extends SearchServerDto> searchServerDtoClass = searchServerDto.getClass();
Class<? extends UserServer> userServerClass = userServer.getClass();
Field[] fields = userServerClass.getDeclaredFields();//获取实体类字节码对象的private属性
for (Field f:fields
) {
FieldAnnoation fieldAnnoation = f.getAnnotation(FieldAnnoation.class);//获取属性上的自定义注解
if (!ObjectUtils.isEmpty(fieldAnnoation)){
String annoationtype = fieldAnnoation.Annoationtype();
if (annoationtype.equals("TableField")){//判断该注解的类型
TableField tableField = f.getAnnotation(TableField.class);//获取TableField注解上的数据库表的名称
Field declaredField = searchServerDtoClass.getDeclaredField(f.getName());//获取searchServerDto的属性
declaredField.setAccessible(true);//设置可访问该属性
Object o = declaredField.get(searchServerDto);//获取searchServerDto对象的属性值
if (!ObjectUtils.isEmpty(o)){
queryWrapper.eq(tableField.value(),o);
}
}else{
TableId tableId = f.getAnnotation(TableId.class);
Field field = searchServerDtoClass.getDeclaredField(f.getName());
field.setAccessible(true);
Object o = field.get(searchServerDto);
if (!ObjectUtils.isEmpty(o)){
queryWrapper.eq(tableId.value(),o);
}
}
}
}
list = userServerService.list(queryWrapper);
}
return Result.success(list);