java - Analog of BeanPropertySqlParameterSource that can handle public fields -
i have simple model, instances of want save in mysql using spring jdbctemplate. use dao saves model objects using simple sql (insert user(id, email...) value (:id, :email...)
). there framework can extract parameters model (when model pojo public fields). so, need similar spring's beanpropertysqlparametersource
, ability work public fields instead of properties.
example of model class:
public class user { public int id; public string email; public string login; public string password; }
i know extending abstractsqlparametersource
can solve problem, hope 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(); (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); } }
as mentionned in comment if reason not wanting getter/setters code clutter, recommend lombok.
here typical model class, can constructed spring (@noargsconstructor
+ @data
getters , setters). @builder
, @allargsconstructor
allow generation of builder pattern fields.
@data @builder @allargsconstructor @noargsconstructor public class subscriptiondata { @id @indexed private uuid key; private string productid; private string receiptstring; private date expirationdate; }
here example of spring service constructor injection. @requiredargsconstructor
creates constructor non-initialized final fields , onconstructor parameter adds spring-@autowired
annotation it. if have many service-dependencies can remove quite clutter.
@slf4j @service @requiredargsconstructor(onconstructor = @__({ @autowired })) public class operatorserviceimpl implements operatorservice { private final whoisservice whoisservice; ... }
Comments
Post a Comment