Define entry as final like this:
for (final Map.Entry<String, String> entry : myMap.entrySet())
Question
I have a map in java.
I want to insert it into database table using JdbcTemplate.
I wrote below code for the same:
for (Map.Entry<String, String> entry : myMap.entrySet()) {
System.out.println(entry.getKey() + " = " + entry.getValue());
this.stgdbJdbcTemplate.batchUpdate(this.myInsertQuery, new BatchPreparedStatementSetter() {
@Override
public void setValues(final PreparedStatement ps, final int i) throws SQLException {
ps.setString(1, entry.getKey());
ps.setString(2, entry.getValue());
}
});
}
Here myMap is a local variable as below:
Map<String, String> myMap = new HashMap<String, String>();
However, I am getting below error:
Cannot refer to a non-final variable entry inside an inner class defined in a different method
What could be the solution to this ?
Updated code:
for (final Map.Entry<String, String> entry : myMap.entrySet()) {
System.out.println(entry.getKey() + " = " + entry.getValue());
this.stgdbJdbcTemplate.batchUpdate(this.myInsertQuery, new BatchPreparedStatementSetter() {
@Override
public void setValues(final PreparedStatement ps, final int i) throws SQLException {
ps.setString(1, entry.getKey());
ps.setString(2, entry.getValue());
}
public int getBatchSize() {
return finalFields.size();
}
});
}
Solution
Define entry as final like this:
for (final Map.Entry<String, String> entry : myMap.entrySet())