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

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. 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


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

Use SQLErrorCodeSQLExceptionTranslator and DAO class with @Repository in Spring. Code example extracted from Stack Overflow:. The configuration file named "sql-error-codes.xml" is by default read from this package. It can be overridden through a file of the same name in the root of the class path (e.g. in the "/WEB-INF/classes" directory), as long as the Spring JDBC package is loaded from the same ClassLoader.


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.

Annotations Used to Configure DAO or Repository Classes. 3. Creating an Embedded Database by Using Spring XML; 3.9.3. Creating an  Spring Repository is very close to DAO pattern where DAO classes are responsible for providing CRUD operations on database tables. However, if you are using Spring Data for managing database operations, then you should use Spring Data Repository interface.


catch (SQLException e) {

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

This means that code using the Spring JDBC abstraction layer does not need to implement JDBC or @Repository public class JdbcCorporateEventDao implements SQLErrorCodeSQLExceptionTranslator is the implementation of  As @Repository serves as a specialization of @Component, it also enable annotated classes to be discovered and registered with application context. This annotation is a general-purpose stereotype annotation which can be applied over DAO classes as well as DDD-style repositories. Individual teams may use as appropriate.


How to use SQLErrorCodeSQLExceptionTranslator and DAO class with @​Repository in Spring? stackoverflow.com. I'm using Spring 3.0.2 and I have a class  In this article first we will understand what DAO is, then the DAO module in Spring. DAO stands for Data Access Object. It’s a design pattern in which a data access object (DAO) is an object that provides an abstract interface to some type of database or other persistence mechanisms.


Spring Repository is very close to DAO pattern where DAO classes are managing database operations, then you should use Spring Data Repository interface. Spring Boot @Repository tutorial shows how to use the @Repository annotation in a Spring application. Tweet Spring is a popular Java application framework and Spring Boot is an evolution of Spring that helps create stand-alone, production-grade Spring based applications easily.


what if i don't annotate DAO classes with @Repository, will that still makes the unchecked exceptions (thrown from DAO methods) eligible for  In spring autowiring, @Autowired annotation handles only wiring part. We still have to define the beans so the container is aware of them and can inject them for us. With @Component, @Repository, @Service and @Controller annotations in place and automatic component scanning enabled, Spring will automatically import the beans into the container and inject to dependencies.