I have a simple model, instances of which I want to save in MySQL using Spring JDBCTemplate. I use DAO that saves model objects using simple sql (insert into user(id, email...) value (:id, :email...)
). Is there any framework that can extract parameters from the model (when the model is just POJO with public fields). So, I need something similar to Spring's BeanPropertySqlParameterSource
, but with the ability to work with public fields instead of properties.
Example of the model class:
public class User {
public int id;
public String email;
public String login;
public String password;
}
I know that extending AbstractSqlParameterSource
can solve my problem, but I hope to find existing framework.
UPD
Implementation based on AbstractSqlParameterSource
:
public class PublicFieldsSqlParameterSource extends AbstractSqlParameterSource {
Map<String, Object> props = new HashMap<>();
public PublicFieldsSqlParameterSource(Object object) {
Field[] fields = object.getClass().getFields();
for (Field field : fields) {
String name = field.getName();
try {
Object value = field.get(object);
props.put(name, value);
} catch (IllegalAccessException ignored) {
}
}
}
@Override
public boolean hasValue(String paramName) {
return props.containsKey(paramName);
}
@Override
public Object getValue(String paramName) throws IllegalArgumentException {
return props.get(paramName);
}
}