Java Remove repeated try, catch, finally boilerplate from DAO

前端 未结 4 1033
心在旅途
心在旅途 2021-01-06 08:06

I have a DAO class with many methods that have a lot of repeated code along the lines of: -

public void method1(...) {
  Connection conn = null;
  try {
             


        
4条回答
  •  佛祖请我去吃肉
    2021-01-06 08:23

    I think what you should use is Spring-JDBC's JdbcTemplate

    Even if you don't use spring to manage your application, you could programmatically use JdbcTemplate to abstract away all the connection management and error handling.

    Example code:

    List actors = this.jdbcTemplate.query(
            "select first_name, last_name from t_actor",
            new RowMapper() {
                public Actor mapRow(ResultSet rs, int rowNum)
                throws SQLException {
                    Actor actor = new Actor();
                    actor.setFirstName(rs.getString("first_name"));
                    actor.setLastName(rs.getString("last_name"));
                    return actor;
                }
            });
    

    As you can see, you deal with the actual query only, not with the infrastructure stuff around it.

提交回复
热议问题