Created
January 24, 2013 18:40
-
-
Save jarek-przygodzki/4626249 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public interface EntityReader<Type> { | |
List<Type> list() throws DAOException; | |
Type uniqueResult() throws DAOException; | |
} | |
import java.sql.ResultSet; | |
import java.sql.SQLException; | |
import java.util.ArrayList; | |
import java.util.List; | |
import app.dao.DAOException; | |
import app.dao.EntityReader; | |
import app.domain.Song; | |
public class SongReader implements EntityReader<Song> { | |
private ResultSet resultSet; | |
public SongReader(ResultSet resultSet) { | |
this.resultSet = resultSet; | |
} | |
@Override | |
public List<Song> list() throws DAOException { | |
List<Song> results = new ArrayList<Song>(); | |
try { | |
while (resultSet.next()) { | |
results.add(readRow()); | |
} | |
} catch (SQLException e) { | |
throw new DAOException(e); | |
} | |
return results; | |
} | |
@Override | |
public Song uniqueResult() throws DAOException { | |
try { | |
if (!resultSet.next()) { | |
return null; | |
} | |
Song song = readRow(); | |
if (resultSet.next()) { | |
throw new DAOException( | |
"Zapytanie nie zwróciło unikalnego rezultatu"); | |
} | |
return song; | |
} catch (SQLException e) { | |
throw new DAOException(e); | |
} | |
} | |
private Song readRow() throws SQLException { | |
Song song = new Song(); | |
long id = resultSet.getLong("song_id"); | |
song.setId(id); | |
String title = resultSet.getString("song_title"); | |
song.setTitle(title); | |
String album = resultSet.getString("song_album"); | |
song.setAlbum(album); | |
String genre = resultSet.getString("song_genre"); | |
song.setGenre(genre); | |
String artist = resultSet.getString("song_artist"); | |
song.setArtist(artist); | |
short year = resultSet.getShort("song_year"); | |
if (!resultSet.wasNull()) { | |
song.setYear(year); | |
} | |
return song; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment