Ciao a tutti,
sto facendo una cosa molto semplice con i generics (che mi suscitano
sempre moltissimo dubbi).
Vabbè il codice è semplicissimo (banale) e penso
non ci sia bisogno di commenti se non la domanda...
Ma è corretto fare come sto facendo?
Ovvero mettere il tipo-parametro nella classe BaseDAO?
E non invece in qualche metodo?
Boh!
Grazie!
codice:
package data;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import util.SQLHandler;
abstract public class BaseDAO<E>
{
protected ArrayList<E> findByQuery( String sql, Object[] params ) throws DataAccessException
{
try
{
SQLHandler handler = new SQLHandler();
ResultSet rs = handler.executeQuery( sql, params );
return fromResultSet( rs );
}
catch( SQLException e )
{
throw new DataAccessException( e.getMessage() );
}
}
abstract protected ArrayList<E> fromResultSet( ResultSet rs ) throws SQLException;
}
codice:
package data;
import business.Author;
import java.sql.SQLException;
import java.sql.ResultSet;
import java.util.ArrayList;
public class AuthorDAO extends BaseDAO<Author>
{
public Author findById( Long id ) throws DataAccessException
{
ArrayList<Author> list = findByQuery( "Select * From authors Where id = ?", new Object[] { id } );
return list.get( 0 );
}
public Author findByCredentials( String username, String password ) throws DataAccessException
{
ArrayList<Author> list = findByQuery( "Select * From authors Where username = ? And password = ?",
new Object[] { username, password } );
return list.get( 0 );
}
protected ArrayList<Author> fromResultSet( ResultSet rs ) throws SQLException
{
ArrayList<Author> list = new ArrayList<Author>();
Author author;
while( rs.next() )
{
author = new Author();
author.setId( rs.getLong( "id" ) );
author.setStatus( Author.Status.valueOf( rs.getString( "status" ) ) );
author.setFirstName( rs.getString( "first_name" ) );
author.setLastName( rs.getString( "last_name" ) );
author.setDisplayEmail( rs.getString( "display_email" ) );
author.setContactEmail( rs.getString( "contact_email" ) );
list.add( author );
}
return list;
}
}