Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where should I put the SQL files in my Java project?

Tags:

I have a Java project which will include a number of large SQL statements for querying the database. My question is: where should I store them?

I'm fairly sure I want each statement its own text file managed by source code control. As Java doesn't support multi-line strings I can't easily put the SQL in my .java files and I don't think I'd want to anyway. At build time I can put these text files in JAR and get the contents with ClassLoader.getResourceAsStream().

So my problem becomes in which directories should I put these files and what should I call them. Ideally I'd like people to tell from the .sql file which Java class uses it. What I definitely don't want is a single directory full of lots of files called things like report1.sql and report3.sql and so on.

My inclination is to put them in the package directory with all the .java files but I have a colleague who doesn't like having anything other than .java files in this tree. So this leads to alternative of a separate directory structure which mirrors the Java packages but this seems like an unnecessary overhead.

So I would be interested to hear what you do with your SQL files.

We're using Netbeans 6.5 in case that will affect your answers.

(This question is similar but sadly the answers are very C# specific, which is good for that question but bad for me.)

like image 936
Dave Webb Avatar asked Mar 03 '09 11:03

Dave Webb


People also ask

Where are SQL queries stored Java?

The best practice should be to store the sql statements in a properties file. And get the statements in the DAO object through an interface to properties files, say java. util. Properties.

How do I run a .SQL file in Java?

You can execute . sql script files in Java using the runScript() method of the ScriptRunner class of Apache iBatis. To this method you need to pass a connection object. Register the MySQL JDBC Driver using the registerDriver() method of the DriverManager class.

Can SQL be used with Java?

Most Java developers interested in employing SQL in their work will do so through JDBC, which allows Java to connect to SQL databases.


1 Answers

In a Java/Maven setting we use as project hierarchy:

project/src/main/java/Package/Class.java project/src/test/java/Package/ClassTest.java project/src/main/resources/Package/resource.properties project/src/test/resources/Package/test_resource.properties 

And in order to answer your question: I would put the SQL-files along with the resources under src/main/resources.

You may want to have a look at this thread.

like image 50
boutta Avatar answered Oct 07 '22 10:10

boutta