0
votes

We are trying to make our spring batch jobs more generic. In this process, we want to make the model object that gets passed between reader, processor and writer generic/dynamic too. If we store the table-name, column-name, type-name in the database, and fetch this info at run time, will we be able to create a model class on the fly, map the data read in the reader and pass it along to the writer?

Is it possible to create MyClass at runtime and do the mappings based on the configuration? RowMapper doesnt accept generic ? So, how do we specify it in the code without actually having an already compiled class at run time?

public class MyRowMapper implements RowMapper {

@Override
public MyClass mapRow(ResultSet rs, int rowNum) throws SQLException {

    MyClass myClass= new MyClass();
            myClass.setName(rs.getString("Name"));
            myClass.setNumber(rs.getLong("Number"));
    return myClass;
}

}
1

1 Answers

2
votes

will we be able to create a model class on the fly, map the data read in the reader and pass it along to the writer?

Yes, using a bytecode library you can create classes at runtime, then assign values using reflection, and pass the object around, but what would be the point?

If no code knows the object ahead of time, even the code using the data needs to use reflection to access the data.

You might as well just use a Map<String, Object>. Or some wrapping class around that, if you need to carry metadata too (e.g. value type when value is null).

Spring can already do this for you. E.g. with JdbcTemplate, instead of calling

<T> List<T> query(String sql, Object[] args, RowMapper<T> rowMapper)

you can just call

List<Map<String,Object>> queryForList(String sql, Object... args)