2021-05-06 发表在 编程语言 16
mybatis plus 根据model的字段,自动拼生成条件
代码语言:javascript复制/**
* 根据model的字段,自动拼生成条件
*/
public class QueryHelper {
public static <T> QueryWrapper<T> getQuery(T model) {
var query = new QueryWrapper<T>();
Arrays.asList(model.getClass().getDeclaredFields()).forEach(field -> {
field.setAccessible(true);
try {
var value = field.get(model);
var column = getColumn(field.getName());
if (value != null) {
query.eq(column, value);
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
});
return query;
}
private static String getColumn(String name) {
var sb = new StringBuffer();
for (int i = 0; i < name.length(); i ) {
char chat = name.charAt(i);
if (chat > 64 && chat < 91) {
sb.append("_");
sb.append(String.valueOf(chat).toLowerCase(Locale.ROOT));
} else {
sb.append(chat);
}
}
return sb.toString();
}
public static void main(String[] args) {
var model = new Channel();
model.setCompanyId("123");
var query = getQuery(model);
System.out.println(query);
}
}