3

I am trying to use Apache Commons Lang's StrSubstitutor to replace variables in a string marked only using prefixes, e.g. like named parameters markjed with : in an SQL query.

Here's the code snippet I am using, which doesn't work.

import com.google.common.collect.ImmutableMap;
import org.apache.commons.lang3.text.StrMatcher;
import org.apache.commons.lang3.text.StrSubstitutor;

Map<String,String> m = ImmutableMap.of("a", 1);

StrSubstitutor strSubstitutor = new StrSubstitutor(m)
        .setVariablePrefix(":")
        .setVariableSuffix("");
System.out.println(strSubstitutor.replace("select a from t where a = :a"));
// expect select a from t where a = 1

Any idea how to do it?

I am trying to implement a custom StrMatcher but am still unsuccessful. Any one has done it before and can share some experience?

Amnon
  • 2,212
  • 1
  • 19
  • 35

1 Answers1

3

After a deep delving into the code of StrSubstitutor I realized it cannot be done using the StrSubstitutor/StrMatcher API. Since Spring's NamedParameterJdbcTemplate does not expose the sql with replaced parameter values, I had to implement my own sql parameter substitutor.

Amnon
  • 2,212
  • 1
  • 19
  • 35