开发者

Organizing JDBC Project

开发者 https://www.devze.com 2023-02-18 01:53 出处:网络
I have some very long SQL statements that need to be run through JDBC. I am wondering what the best procedure is for organizing them? Should I make a separate class, define them as va开发者_如何转开发

I have some very long SQL statements that need to be run through JDBC. I am wondering what the best procedure is for organizing them? Should I make a separate class, define them as va开发者_如何转开发riables and just reference those class variables from my main application class?

Or should I just put them into the application class and deal with it being hard to read?

Any help would be great.


I don't like the idea of a separate file. I'd put them in the file where they're used, because I don't want to have to go somewhere else just to figure out what the database is doing.

I'd make them static final Strings so I don't keep recreating them each time. If you're concatenating or using StringBuilder you're probably doing it wrong.

I'd be sure to use PreparedStatements everywhere. You'll be safe from SQL injection and your code will be better for it, too.

Have a CRUD interface for objects, using the Data Access Object pattern:

public interface FooDao<K, T>
{
   T find(Long id);
   List<T> find();
   K save(T instance);
   void delete(T instance);   
}


The one benefit I can think of for keeping them together is if you change the data model it is easy to go to the one place where are the queries are and find the affected queries.

If you have a small number of queries I wouldn't worry too much, just format them so they are easily readable (tho that goes regardless of the approach you use!)

If you want to go the class-with-string-variables route and if your number of queries is going to be large (>100) then I would group them up into a few different classes.


It might be possible to store the scripts in separate files which you read from your app. If the scripts are SQL, then having a separate file for them would make them runnable directly for debugging.

If you have large query statements, you could also define views.


I think the easiest is to either read the SQL from a file if there is a lot, or to make a bunch of prepared statements and just don't wrap them.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号