简体   繁体   English

使用 spring jdbctemplate 从数据库填充 pojo

[英]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?通过允许 spring 自动检测与列匹配的数据成员的名称,是否可以在不创建映射器的情况下填充 object (pojo)? I was expecting to have something similar to SimpleJdbcInsert in which I use as follows:我期待有类似于 SimpleJdbcInsert 的东西,我在其中使用如下:

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.根据您使用的 Spring 版本,您可以使用BeanPropertyRowMapper ,它将 map 列到 POJO 中的变量。 It will map either direct matches or convert underscore style database names to camel case style variable names in your Java class.它将 map 直接匹配或将下划线样式数据库名称转换为 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.老实说,我不知道 spring 但使用 apache 中的 Bean 常用工具很容易实现通用的 JDBC 模板。

You are using a SimpleJdbcInsert, I think you mean SimpleJdbcTemplate that retrun results?您正在使用 SimpleJdbcInsert,我认为您的意思是 SimpleJdbcTemplate 重新运行结果?

The good way is using a RowMapper or a ResultSetExtractor from Spring JDBC.好的方法是使用来自 Spring JDBC 的 RowMapper 或 ResultSetExtractor。

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).但是您可以使用 SimpleJdbcTemplate 中的 queryForMap 方法跳过包装器,并使用方法 populate(Object bean, Map properties) 将结果从 apache commons beanutils 传递到 BeanUtils 中。

Althought, I think the best solution is RowMapper or a ResultSetExtractor.尽管如此,我认为最好的解决方案是 RowMapper 或 ResultSetExtractor。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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