如何使用地图列表在Spring中执行批量更新?
Spring的新手,我试图将List<Map>
插入表中。 到目前为止,我一直在使用SqlParameterSource
进行批量更新,这在向它们提供java bean时可以正常工作。 像这样的东西:
@Autowired private NamedParameterJDBCTemplate v2_template; public int[] bulkInsertIntoSiteTable(List list){ SqlParameterSource[] batch = SqlParameterSourceUtils .createBatch(list.toArray()); int[] updateCounts = v2_template .batchUpdate( "insert into sitestatus (website, status, createdby) values (:website, :status, :username)", batch); return updateCounts; }
但是,我尝试使用相同的技术代替bean的地图列表,它失败了(这是正确的)。
public int[] bulkInsertIntoSiteTable(List<Map> list){ SqlParameterSource[] batch = SqlParameterSourceUtils .createBatch(list.toArray()); int[] updateCounts = v2_template .batchUpdate( "insert into sitestatus (website, status, createdby) values (:website, :status, :username)", batch); return updateCounts; }
上面的代码失败,出现以下exception:
Exception in thread "main" org.springframework.dao.InvalidDataAccessApiUsageException: No value supplied for the SQL parameter 'website': Invalid property 'website' of bean class [org.springframework.util.LinkedCaseInsensitiveMap]: Bean property 'website' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter? at org.springframework.jdbc.core.namedparam.NamedParameterUtils.buildValueArray(NamedParameterUtils.java:322) at org.springframework.jdbc.core.namedparam.NamedParameterBatchUpdateUtils$1.setValues(NamedParameterBatchUpdateUtils.java:45) at org.springframework.jdbc.core.JdbcTemplate$4.doInPreparedStatement(JdbcTemplate.java:893) at org.springframework.jdbc.core.JdbcTemplate$4.doInPreparedStatement(JdbcTemplate.java:1) at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:587) at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:615) at org.springframework.jdbc.core.JdbcTemplate.batchUpdate(JdbcTemplate.java:884) at org.springframework.jdbc.core.namedparam.NamedParameterBatchUpdateUtils.executeBatchUpdateWithNamedParameters(NamedParameterBatchUpdateUtils.java:40) at org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate.batchUpdate(NamedParameterJdbcTemplate.java:303) at tester.utitlies.dao.VersionTwoDao.bulkInsertIntoSites(VersionTwoDao.java:21) at tester.utitlies.runner.Main.main(Main.java:28)
它失败了,因为它认为列表是一批bean,我想。 我找不到在Spring中使用地图列表和使用NamedParameterJDBCTemplate
执行批量更新的方法。 请指教。
根据Spring NamedParameterJDBCTemplate
文档, 此处可以使用此方法通过地图进行批量更新。
int[] batchUpdate(String sql, Map
真正的挑战是从相应的List
获取一个Map
数组。 我使用以下代码来获取arrays并执行批量更新。
public static Map[] getArrayData(List