简体   繁体   中英

Populating pojo from a db using spring jdbctemplate

Is it possible to populate an object (pojo) without creating a mapper, by allowing spring to auto detect the names of the data members that matches the columns? I was expecting to have something similar to SimpleJdbcInsert in which I use as follows:

new SimpleJdbcInsert(dataSource).withTableName("actors").execute(new BeanPropertySqlParameterSource(actor));

Thanks!

Depending on which version of Spring you are using, you can use the BeanPropertyRowMapper which will map columns to variables in your POJO. It will map either direct matches or convert underscore style database names to camel case style variable names in your Java class.

Honestly I don't know for spring but using Bean common utils from apache it is easy to implement a generic JDBC template doing exactly that.

You are using a SimpleJdbcInsert, I think you mean SimpleJdbcTemplate that retrun results?

The good way is using a RowMapper or a ResultSetExtractor from Spring JDBC.

But you can skip the wrapper by using the method queryForMap from SimpleJdbcTemplate and pass the results in BeanUtils from apache commons beanutils with the methods populate(Object bean, Map properties).

Althought, I think the best solution is RowMapper or a ResultSetExtractor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM