java动态⽣成SQL中的where条件
在编写接⼝的时候,查询关系型数据库是经常有的事情,如果我们不⽤hibernate,也不想写⼤量⽆聊的SQL,那该怎么办?其实⽤反射的⽅式获取表的表名和字段名⾮常容易,但是拼接where条件则⽐较难,我尝试了⼀下,也是可以做到的。
代码有些冗长,还有待改进
@AllArgsConstructor
@Data
public class Condition {
private String conditionName;
private String operator;
private Boolean isString;
private Object conditionValue;
/**
* 构建有关键字占位符的SQL条件语句
* @param conditions
* @return
*/
public static String toSql(List<Condition> conditions) {
StringBuilder sb = new StringBuilder("where ");
int size = conditions.size();
for (int i = 0; i < size; i++) {
Condition condition = (i);
String conditionName = ConditionName();
Object conditionValue = ConditionValue();
sb.append(conditionName)
.Operator());
boolean conditionType = IsString();
if (conditionType) {
sb.append(String.format(" '%s' ",conditionValue));
} else {
sb.append(String.format(" %s ",conditionValue));
}
if (i != size - 1) {
sql自学难吗sb.append(" and ");
}
}
String();
}
public static void main(String[] args) {
List<Condition> conditions = new ArrayList<>();
Condition bizmonth = new Condition("bizmonth", "=", true,"2021-06");
Condition tenant_code = new Condition("tenant_code", "=", false,"0385");
Condition create_time = new Condition("create_time", ">", true,"2021-06-09 10:08:00");
conditions.add(bizmonth);
conditions.add(tenant_code);
conditions.add(create_time);
String sql = toSql(conditions);
System.out.println(sql);
}
}
结果:
where bizmonth= '2021-06'  and tenant_code= 0385  and create_time> '2021-06-09 10:08:00'

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。