pugr
pugr

Reputation: 55

One DAO per multiple tables with same structure

I'm using Spring and Oracle DB and due to the need for storing different XML files in separate tables containing the same columns, I would like to use a single DAO for operations on these tables. I'm new to Spring, so I'm asking if this approach is possible and if so, then how it can be done.

Upvotes: 2

Views: 3256

Answers (1)

Sean Patrick Floyd
Sean Patrick Floyd

Reputation: 299178

You can do it very easily with Spring JDBC's JdbcTemplate.

  • Create an abstract Entity Base class

    public abstract class YourBaseEntityClass {
        private String fooProperty;
        private Long barProperty;
        // + getters and setters
    }
    
  • Create a generic DAO Interface

    public interface Dao<T> {
        T get(Long id);
        // you'll probably want more methods here :-)
    }
    
  • Create a Generic abstract RowMapper

    public abstract class GenericRowMapper<T extends YourBaseEntityClass>
    implements RowMapper<T> {
    
        public T mapRow(final ResultSet rs, final int rowNum)
        throws SQLException {
            final T entity = instantiateEntityClass();
            entity.setFooProperty(rs.getString("foo"));
            entity.setBarProperty(rs.getLong("bar"));
            return entity;
        }
    
        protected abstract T instantiateEntityClass();
    
    }
    
  • Create a generic DAO Implementation

    public class GenericJdbcDao<T> implements Dao<T> {
    
        private String tableName;
        public void setTableName(final String tableName) {
            this.tableName = tableName;
        }
    
        private JdbcTemplate jdbcTemplate;
        public void setJdbcTemplate(final JdbcTemplate jdbcTemplate) {
            this.jdbcTemplate = jdbcTemplate;
        }
    
        private RowMapper<T> rowMapper;
        public void setRowMapper(final RowMapper<T> rowMapper) {
            this.rowMapper = rowMapper;
        }
    
        public T get(final Long id) {
            return jdbcTemplate.queryForObject(
                // please don't do it like this, this is just a quick example
                "select * from " + tableName + " where id=" + id, rowMapper);
        }
    }
    

Now, for every specific entity type, you need to:

  1. subclass YourBaseEntityClass
  2. subclass GenericRowMapper, so that it creates the new entity type
  3. with Spring, configure a new GenericDao instance with the correct table name and rowmapper

That's it!

Upvotes: 2

Related Questions