简体   繁体   English

如何在Spring中使用SQLErrorCodeSQLExceptionTranslator和DAO类与@Repository?

[英]How to use SQLErrorCodeSQLExceptionTranslator and DAO class with @Repository in Spring?

I'm using Spring 3.0.2 and I have a class called MovieDAO that uses JDBC to handle the db. 我正在使用Spring 3.0.2,我有一个名为MovieDAO的类,它使用JDBC来处理数据库。 I have set the @Repository annotations and I want to convert the SQLException to the Spring's DataAccessException I have the following example: 我已经设置了@Repository注释,我想将SQLException转换为Spring的DataAccessException我有以下示例:

   @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 我不知道如何获得翻译器,我不想扩展任何Spring类,因为这就是我使用@Repository注释的原因

You must provide a bean-post processor to get your goal 你必须提供一个bean-post处理器来实现你的目标

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

Or use SQLExceptionSubclassTranslator 或者使用SQLExceptionSubclassTranslator

private SQLExceptionTranslator sqlExceptionTranslator = new SQLExceptionSubclassTranslator();

catch(SQLException e) {
    throw sqlExceptionTranslator.doTranslate("<WHICH_TASK>", "<WHICH_SQL_QUERY>", e);
}

instead 代替

JDBC doesn't work very well with @Repository and automatic exception translation, because SQLException is not a runtime exception. JDBC在使用@Repository和自动异常转换时效果不佳,因为SQLException不是运行时异常。 @Repository -style exception translation only really works with data access APIs that use runtime exceptions, eg Hibernate and JPA. @Repository style异常转换仅适用于使用运行时异常的数据访问API,例如Hibernate和JPA。

The @Repository annotation is used by the Spring context to auto-generate a proxy wrapper around your DAO, translating the exceptions as they get thrown. Spring上下文使用@Repository注释来自动生成DAO周围的代理包装器,在抛出异常时对其进行转换。 This only works with runtime exceptions, though. 但这仅适用于运行时异常。 Specifically, if your DAO implementation class methods throw SQLException , then so must your interface method signatures, and so must the proxy wrapper, and so the client code must handle that exception, which all rather defeats the point of exception translation. 具体来说,如果您的DAO实现类方法抛出SQLException ,那么您的接口方法签名也必须如此,代理包装器也必须如此,因此客户端代码必须处理该异常,这些异常都会使异常转换失败。

For JDBC, some coupling to the Spring API is usually necessary, either by extending JdbcDaoSupport and using getExceptionTranslator() , or manually constructing your own SQLExceptionTranslator instance. 对于JDBC,通常需要通过扩展JdbcDaoSupport和使用getExceptionTranslator()或手动构建自己的SQLExceptionTranslator实例来与Spring API进行一些耦合。 Either way, you need to catch SQLException inside the DAO and translate it into a DataAccessException . 无论哪种方式,您都需要在DAO中捕获SQLException并将其转换为DataAccessException

catch (SQLException e) { catch(SQLException e){

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM