Spring と Oracle DB を使用していますが、同じ列を含む別のテーブルに異なる XML ファイルを格納する必要があるため、これらのテーブルの操作に単一の DAO を使用したいと考えています。私はSpringが初めてなので、このアプローチが可能かどうか、可能であればどうすればよいかを尋ねています。
3033 次
1 に答える
2
Spring JDBCのJdbcTemplateを使用すると、非常に簡単に実行できます。
抽象エンティティ ベース クラスを作成する
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); } }
ここで、特定のエンティティ タイプごとに、次のことを行う必要があります。
- サブクラス
YourBaseEntityClass
- subclass
GenericRowMapper
、新しいエンティティ タイプを作成するため - Spring では、正しいテーブル名とローマッパーを使用して新しい GenericDao インスタンスを構成します
それでおしまい!
于 2011-04-29T12:27:35.057 に答える