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

发布于 2024-09-01 07:04:19 字数 1857 浏览 7 评论 0原文

我正在使用 Spring 3.0.2,并且有一个名为 MovieDAO 的类,它使用 JDBC 来处理数据库。我已经设置了 @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;
        }
}

我不知道如何获取 Translator 并且我不想扩展任何 Spring 类,因为这就是原因我正在使用 @Repository 注释

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

冷︶言冷语的世界 2024-09-08 07:04:19

您必须提供一个bean后处理器才能实现您的目标

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

或使用 SQLExceptionSubclassTranslator

private SQLExceptionTranslator sqlExceptionTranslator = new SQLExceptionSubclassTranslator();

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

代替

You must provide a bean-post processor to get your goal

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

Or use SQLExceptionSubclassTranslator

private SQLExceptionTranslator sqlExceptionTranslator = new SQLExceptionSubclassTranslator();

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

instead

旧城烟雨 2024-09-08 07:04:19

JDBC 不能很好地与 @Repository 和自动异常转换配合使用,因为 SQLException 不是运行时异常。 @Repository 式异常转换 仅适用于使用运行时异常的数据访问 API,例如 Hibernate 和 JPA。

Spring 上下文使用 @Repository 注释来自动生成 DAO 周围的代理包装器,并在抛出异常时对其进行转换。不过,这只适用于运行时异常。具体来说,如果您的 DAO 实现类方法抛出 SQLException,那么您的接口方法签名也必须如此,代理包装器也必须如此,因此客户端代码必须处理该异常,而这一切都违背了例外翻译。

对于 JDBC,通常需要与 Spring API 进行一些耦合,可以通过扩展 JdbcDaoSupport 并使用 getExceptionTranslator(),或者手动构造自己的 SQLExceptionTranslator实例。无论哪种方式,您都需要在 DAO 中捕获 SQLException 并将其转换为 DataAccessException

JDBC doesn't work very well with @Repository and automatic exception translation, because SQLException is not a runtime exception. @Repository-style exception translation only really works with data access APIs that use runtime exceptions, e.g. Hibernate and 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. 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.

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. Either way, you need to catch SQLException inside the DAO and translate it into a DataAccessException.

蛮可爱 2024-09-08 07:04:19

catch (SQLException e) {

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

catch (SQLException e) {

                    throw new DataAccessException("some message",e);
        }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文