what is the best place to place SQL queries in an application?
The queries might be big and requires formatting.
Appending the query using StringBuilder looks very cluttered.
Storing them in files and reading them every time when a request is made – looks like a bad idea.(but i think reading from the file can be put in a static block)
Keep the SQL query in a resource file that you read to a constant at class load time:
That way you can use your favorite editor to edit the SQL, but you still get the query in a constant in java.
If you do this a lot, extract the code to a helper method:
and use that in your static blocks:
In my opinion, different languages should always be separated. It’s an awful practice to assemble SQL, HTML, XML, JavaScript etc. from Java code. Use plain templates or template engines like Velocity whenever possible. That gives you many benefits, one of them being that you can change the template without recompiling the java class.
PS: I am using Apache Commons / IO in the above code, but it’s not necessary, just easier.