Consider data layer tools

Many applications store data in a relational database. The standard JDBC API is used to interact with relational databases, but it's a bit low level. It's not hard to define a few helper classes that will encapsulate the bulk of repeated JDBC code. But even so, many applications will benefit from using tools that operate on top of the JDBC API.

Examples of such tools include:

These tools generally fall into two categories:

Although ORM tools are currently popular, some argue that they should be avoided. In brief:

As an example of the relative simplicity of tools which give primacy to SQL, and not objects, here's an example of a Data Access Object (DAO) implemented with web4j. The actual SQL statements are placed in .sql text files placed near the corresponding DAO (usually in the same directory).
FETCH_PREFERENCES {
  SELECT Id, LoginName, ScreenName FROM Users WHERE LoginName=?
}
CHANGE_PREFERENCES {
  UPDATE Users SET  ScreenName=? WHERE LoginName=?
}
Entries in the above .sql file are referenced in code using SqlId objects, such as FETCH_PREFERENCES:

import static hirondelle.predict.main.preferences.PreferencesAction.CHANGE_PREFERENCES;
import static hirondelle.predict.main.preferences.PreferencesAction.FETCH_PREFERENCES;
import hirondelle.web4j.database.DAOException;
import hirondelle.web4j.database.Db;
import hirondelle.web4j.security.SafeText;

/**
 Data Access Object for user {@link Preferences}. 
*/
public final class PreferencesDAO {
  
  /** Fetch the {@link Preferences} for a given user. */ 
  public Preferences fetch(SafeText aUserId) throws DAOException {
    return Db.fetch(Preferences.class, FETCH_PREFERENCES, aUserId);
  }
  
  /** Change the {@link Preferences} for a given user. */
  void change(Preferences aPreferences) throws DAOException {
    Db.edit(
      CHANGE_PREFERENCES, 
      aPreferences.getScreenName(), 
      aPreferences.getLoginName()
    );
  }
} 

That's all there is to it. There's no mapping involved.

See Also :
Simplify database operations
Would you use this technique?
Yes   No   Undecided   
© 2014 Hirondelle Systems | Source Code | Contact | License | RSS
Individual code snippets can be used under this BSD license - Last updated on September 21, 2013.
Over 2,000,000 unique IPs last year - Built with WEB4J.
- In Memoriam : Bill Dirani -