The following are methods I currently have in an Abstract DAO class. If there are concurrent calls, are they safe as they are or should synchronization be used? I know synchronization should be used if there is a reference to an attribute outside the scope of a method but it’s unclear to me how should things be handled with an outside ressource.
public Connection getConnection() {
// Call to singleton handling JDBC stuff
return Database.getInstance().getCon();
}
public boolean isConnectionAvailable(){
if( getConnection() != null ){
return true;
}
return false;
}
public PreparedStatement getPreparedStatement( String sqlStatement ){
Connection connection = getConnection();
PreparedStatement pS = null;
if( connection != null ){
try {
pS = connection.prepareStatement( sqlStatement );
} catch (SQLException e) {
return null;
}
}
return pS;
}
Edit: I might reformulate this question to include information on writing DAOs as it’s what’s important here.
I don’t agree with this implementation at all.
First, DAOs should be given their connection information by the services that own units of work and transactions.
Second, I don’t see an interface.
Third, I don’t see model or domain objects.
Fourth, prepared statements should only be part of the internal implementation. If they’re leaking out of your DAO, you’re doing it wrong.
Fifth, passing a prepared statement out of the object makes responsibility for closing it and cleaning up far less clear. Your DAO will die a resource leak death in no time.
Here’s an interface for a generic DAO. You’ll notice that it’s all CRUD operations, with no mention of connnections or any interfaces from java.sql package:
You can go a long way with this. It’s a better abstraction. The
Tis your business object type, andKis the primary key.