查询条件拼接SQL sqljava 

  • sql |java
  • 2022-07-15 19:14:02
public static void query() throws ParseException {
		String jsonStr = "{applyNo:{like:'A001'}, name:{=:'张三'}, amt:{>: 600, oper: 'or', <: 1000}}";

		JSONObject json = new JSONObject(jsonStr);

		Iterator<String> iter = json.keys();

		StringBuffer jpql = new StringBuffer("select * from table");

		// 放置参数
		List<Object> params = new ArrayList<Object>();
		int index = 0;
		
		boolean firstFlag = true;
		while (iter.hasNext()) {
			// 查询字段
			String key = iter.next();
			JSONObject obj = json.getJSONObject(key);

			if (firstFlag) {
				firstFlag = false;
				jpql.append(" where ");
			} else {
				jpql.append(" and ");
			}

			jpql.append(key).append(" ");

			Iterator<String> valIter = obj.keys();

			while (valIter.hasNext()) {
				// 查询条件
				String valKey = valIter.next();

				// 不是操作符,就执行
				if (!"oper".equals(valKey)) {

					Object valObj = obj.get(valKey);

					jpql.append(valKey).append(" ?_").append(index).append(" ");

					if (valIter.hasNext()) {
						Object oper = obj.get("oper");
						jpql.append(" ").append(oper).append(" ");
					}
					
					params.add(valObj);
					index++;
				}
			}

		}

		System.out.println(jpql);
		System.out.println(Arrays.toString(params.toArray()));
	}

猜你喜欢