2010-05-08 54 views
4

我使用的是Spring 3.0.2,我有一个叫做MovieDAO的类,它使用JDBC来处理数据库。我已经设置了@Repository注解,我想为SQLException转换为春天的DataAccessException我下面举个例子:如何在Spring中使用带有@Repository的SQLErrorCodeSQLExceptionTranslator和DAO类?

@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; 
     } 
} 

我不知道如何让翻译,我不希望任何延伸Spring类,因为这就是为什么我使用@Repository注解

回答

4

你必须提供一个bean-后处理器让你的目标

<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/> 

或者使用SQLExceptionSubclassTranslator

代替

1

JDBC不@Repository和自动异常翻译工作得很好,因为SQLException是不是一个运行时异常。 @Repository-style exception translation只适用于使用运行时异常的数据访问API,例如Hibernate和JPA。

Spring上下文使用@Repository注释来自动生成围绕您的DAO的代理封装器,并在引发异常时转换它们。但这只适用于运行时异常。特别是,如果您的DAO实现类方法抛出SQLException,那么您的接口方法签名必须如此,并且代理包装器也必须如此,因此客户端代码必须处理该异常,这完全违背了异常转换的要点。

对于JDBC,通常需要一些与Spring API的耦合,或者通过扩展JdbcDaoSupport并使用getExceptionTranslator(),或手动构建自己的SQLExceptionTranslator实例。无论哪种方式,您需要在DAO内部捕获SQLException并将其翻译为DataAccessException

0

赶上(的SQLException E){

    throw new DataAccessException("some message",e); 
     }