Reputation: 55
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
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:
YourBaseEntityClass
GenericRowMapper
, so that it creates the new entity typeThat's it!
Upvotes: 2