Java Programming – Where should SQL statements be stored? [closed]

Usually, the more the application grows in terms of size and/or reusability, the more the need is to externalize/abstractize the SQL statements.

Hardcoded (as static final constants) is the first step.
Stored in a file (properties/xml file) is the next step.
Metadata driven (as done by an ORM like Hibernate/JPA) is the last step.

Hardcoded has the disadvantage that your code is likely to become DB-specific and that you need to rewrite/rebuild/redistribute on every change. Advantage is that you have it in 1 place.

Stored in a file has the disadvantage that it can become unmaintainable when the application grows. Advantage is that you don’t need to rewrite/rebuild the app, unless you need to add an extra DAO method.

Metadata driven has the disadvantage that your model code is very tight coupled with the database model. For every change in the database model you’ll need to rewrite/rebuild/redistribute code. Advantage is that it is very abstract and that you can easily switch from DB server without the need to change your model (but ask yourself now: how often would a company switch from DB server? likely at least only once per 3 years, isn’t it?).

I won’t call stored procedures a “good” solution for this. They have an entirely different purpose. Even though, your code would be dependent on the DB / configuration used.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)