Created
May 22, 2012 11:22
-
-
Save awilmore/2768446 to your computer and use it in GitHub Desktop.
SQL Statement Loader via Spring IO Resource
This file contains hidden or 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
import java.io.BufferedReader; | |
import java.io.File; | |
import java.io.FileReader; | |
import java.io.IOException; | |
import java.util.Arrays; | |
import java.util.List; | |
import org.slf4j.Logger; | |
import org.slf4j.LoggerFactory; | |
import org.springframework.core.io.Resource; | |
import org.springframework.jdbc.core.JdbcTemplate; | |
import org.springframework.stereotype.Component; | |
@Component | |
public class StatementLoader { | |
final Logger logger = LoggerFactory.getLogger(this.getClass()); | |
public void executeStatements(Resource resource, JdbcTemplate jdbcTemplate) { | |
try { | |
List<String> statements = loadStatements(resource); | |
for(String statement: statements) { | |
logger.info("Executing statement: " + statement); | |
jdbcTemplate.execute(statement); | |
} | |
} catch(IOException e) { | |
throw new RuntimeException(e); | |
} | |
} | |
private List loadStatements(Resource resource) throws IOException { | |
String contents = loadContents(resource.getFile()); | |
List statements = Arrays.asList(contents.split(";")); | |
return statements; | |
} | |
private String loadContents(File resource) throws IOException { | |
StringBuffer contents = new StringBuffer(); | |
BufferedReader reader = new BufferedReader(new FileReader(resource)); | |
String buf = null; | |
while((buf = reader.readLine()) != null) { | |
contents.append(buf); | |
} | |
reader.close(); | |
return contents.toString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment