统一封装动态组装SQL语句实现逻辑

1.封装替换符工具类

	public static String replacePlaceholders(String value, final Properties properties) {

		// 可选占位符
		final Pattern optionalPattern = Pattern.compile("@\\[(.*?)\\]");

		// 必选占位符
		final Pattern requiredPattern = Pattern.compile("\\$\\{param\\.([^}]+)\\}");

		// 处理可选占位符
		Matcher optionalMatcher = optionalPattern.matcher(value.toString());
		StringBuffer optionalMatchResult = new StringBuffer();
		while (optionalMatcher.find()) {
			String optionalContent = optionalMatcher.group(1);
			Matcher innerRequiredMatcher = requiredPattern.matcher(optionalContent);
			boolean containsEmptyRequired = false;

			while (innerRequiredMatcher.find()) {
				String key = innerRequiredMatcher.group(1);
				String replacement = properties.getProperty(key);
				if (replacement == null || replacement.isEmpty()) {
					containsEmptyRequired = true;
					break;
				}
			}

			if (containsEmptyRequired) {
				optionalMatcher.appendReplacement(optionalMatchResult, "");
			} else {
				optionalMatcher.appendReplacement(optionalMatchResult, Matcher.quoteReplacement(optionalContent));
			}
		}
		optionalMatcher.appendTail(optionalMatchResult);

		// 处理必选占位符
		Matcher requiredMatcher = requiredPattern.matcher(optionalMatchResult);
		StringBuffer requiredMatchResult = new StringBuffer();
		while (requiredMatcher.find()) {
			String key = requiredMatcher.group(1);
			String replacement = properties.getProperty(key);
			if (replacement == null) {
				throw new IllegalArgumentException("Required placeholder ${" + key + "} not found in properties");
			}
			requiredMatcher.appendReplacement(requiredMatchResult, Matcher.quoteReplacement(replacement));
		}
		requiredMatcher.appendTail(requiredMatchResult);

		// 返回最终结果
		return requiredMatchResult.toString();
	}

2.样例调用

public static void main(String[] args) {
		Properties properties = new Properties();
		properties.setProperty("year", "\"2023\"");
		properties.setProperty("unitIndustry", "[\"国企\", \"民企\"]");
		String template = "SELECT * from xxx where budget_year = ${param.year} @[and unit_industry_name in ${param.unitIndustry}] @[and unit_industry_name1 in ${param.unitIndustry1}]";
		try {
			String result = DacpPlaceholderReplacer.replacePlaceholders(template, properties);
			System.out.println(result);
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		}
	}

3.运行结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值