Created
March 11, 2012 20:43
-
-
Save kdonald/2018152 to your computer and use it in GitHub Desktop.
Spring JDBC Extension - Externalized SQL strings
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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