[英]Is it possible to create a Java Model Object at runtime and map the fields from the Spring Batch Reader dynamically?
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? 是否可以在运行时创建MyClass并根据配置进行映射? RowMapper doesnt accept generic ?
RowMapper不接受泛型吗? So, how do we specify it in the code without actually having an already compiled class at run time?
那么,我们如何在代码中指定它而不在运行时实际拥有一个已编译的类呢?
public class MyRowMapper implements RowMapper { 公共类MyRowMapper实现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;
}
}
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>
. 您也可以只使用
Map<String, Object>
。 Or some wrapping class around that, if you need to carry metadata too (eg value type when value is null). 或者围绕它的一些包装类,如果您也需要携带元数据(例如,当value为null时的值类型)。
Spring can already do this for you. Spring已经可以为您做到这一点。 Eg with
JdbcTemplate
, instead of calling 例如,使用
JdbcTemplate
,而不是调用
<T> List<T> query(String sql, Object[] args, RowMapper<T> rowMapper)
you can just call 你可以打电话
List<Map<String,Object>> queryForList(String sql, Object... args)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.