【问题标题】:One DAO per multiple tables with same structure每个具有相同结构的多个表一个 DAO
【发布时间】:2011-04-22 14:07:11
【问题描述】:

我正在使用 Spring 和 Oracle DB,由于需要将不同的 XML 文件存储在包含相同列的单独表中,我想使用单个 DAO 对这些表进行操作。我是 Spring 新手,所以我想问这种方法是否可行,如果可以,那么如何实现。

【问题讨论】:

  • 您需要显着改进您的问题才能获得答案。特别是,提供一个你正在谈论的例子。就目前而言,它相当模糊,这可能是没有人回答的原因。

标签: java spring jdbc dao spring-jdbc


【解决方案1】:

您可以使用Spring JDBCJdbcTemplate 轻松完成。

  • 创建一个抽象实体基类

    public abstract class YourBaseEntityClass {
        private String fooProperty;
        private Long barProperty;
        // + getters and setters
    }
    
  • 创建通用 DAO 接口

    public interface Dao<T> {
        T get(Long id);
        // you'll probably want more methods here :-)
    }
    
  • 创建通用抽象 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();
    
    }
    
  • 创建一个通用的 DAO 实现

    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);
        }
    }
    

现在,对于每个特定的实体类型,您需要:

  1. 子类YourBaseEntityClass
  2. 子类GenericRowMapper,以便创建新的实体类型
  3. 使用 Spring,使用正确的表名和行映射器配置新的 GenericDao 实例

就是这样!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-27
    • 1970-01-01
    • 2015-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多