How to use SQLErrorCodeSQLExceptionTranslator and DAO class with @Repository in Spring?
Posted
by GuidoMB
on Stack Overflow
See other posts from Stack Overflow
or by GuidoMB
Published on 2010-05-08T01:26:04Z
Indexed on
2010/05/08
1:28 UTC
Read the original article
Hit count: 335
I'm using Spring 3.0.2 and I have a class called MovieDAO that uses JDBC to handle the db. I have set the @Repository annotations and I want to convert the SQLException to the Spring's DataAccessException I have the following example:
@Repository
public class JDBCCommentDAO implements CommentDAO {
static JDBCCommentDAO instance;
ConnectionManager connectionManager;
private JDBCCommentDAO() {
connectionManager = new ConnectionManager("org.postgresql.Driver", "postgres", "postgres");
}
static public synchronized JDBCCommentDAO getInstance() {
if (instance == null)
instance = new JDBCCommentDAO();
return instance;
}
@Override
public Collection<Comment> getComments(User user) throws DAOException {
Collection<Comment> comments = new ArrayList<Comment>();
try {
String query = "SELECT * FROM Comments WHERE Comments.userId = ?";
Connection conn = connectionManager.getConnection();
PreparedStatement stmt = conn.prepareStatement(query);
stmt = conn.prepareStatement(query);
stmt.setInt(1, user.getId());
ResultSet result = stmt.executeQuery();
while (result.next()) {
Movie movie = JDBCMovieDAO.getInstance().getLightMovie(result.getInt("movie"));
comments.add(new Comment(result.getString("text"), result.getInt("score"), user, result.getDate("date"), movie));
}
connectionManager.closeConnection(conn);
} catch (SQLException e) {
e.printStackTrace();
//CONVERT TO DATAACCESSEXCEPTION
}
return comments;
}
}
I Don't know how to get the Translator and I don't want to extends any Spring class, because that is why I'm using the @Repository annotation
© Stack Overflow or respective owner