Skip to content

Instantly share code, notes, and snippets.

@kdonald
Created March 11, 2012 20:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kdonald/2018152 to your computer and use it in GitHub Desktop.
Save kdonald/2018152 to your computer and use it in GitHub Desktop.
Spring JDBC Extension - Externalized SQL strings
// example api usage:
String sql = SqlUtils.sql(new ClassPathResource("complex.sql", getClass()));
// example complex.sql
SELECT {a bunch of fields}
FROM {table}
INNER JOIN {other} ON ...
INNER JOIN {other} ON ...
INNER JOIN (subquery) v ON ...
LEFT OUTER JOIN {other} ...
WHERE {expression};
// basic implementation:
import java.io.IOException;
import java.io.LineNumberReader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.util.StringUtils;
public class SqlUtils {
private static final String COMMENT_PREFIX = "--";
public static String sql(Resource resource) {
return sql(new EncodedResource(resource));
}
public static String sql(EncodedResource resource) {
LineNumberReader reader = null;
try {
reader = new LineNumberReader(resource.getReader());
String currentStatement = reader.readLine();
StringBuilder scriptBuilder = new StringBuilder();
while (currentStatement != null) {
if (StringUtils.hasText(currentStatement)
&& (COMMENT_PREFIX != null && !currentStatement.startsWith(COMMENT_PREFIX))) {
if (scriptBuilder.length() > 0) {
scriptBuilder.append('\n');
}
scriptBuilder.append(currentStatement);
}
currentStatement = reader.readLine();
}
return scriptBuilder.toString();
} catch (IOException e) {
throw new IllegalArgumentException("Unable to read SQL resource", e);
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment