I have a bean which has two fields
1: Map<String,String> client
2: String target
I have to write this bean to the database.
I have a query "INSERT INTO my_table(client_key ,client_value ,target) VALUES(?,?,?)"
So every key-value pair and the String target should be inserted into the table.
How do I go about doing this efficiently ? The batch update documentation only show to write with lists.
Edit: Here's what I have tried so far.
This is my bean class:
public class FinalBean {
private Map<String,String> client;
private String target;
public Map<String, String> getClient() {
return client;
}
public void setClient(Map<String, String> client) {
this.client = client;
}
public String getTarget() {
return target;
}
public void setTarget(String target) {
this.target = target;
}
}
This is how I attempted to write the bean.
public void saveFinalBean(final FinalBean bean)
{
String insert_query="INSERT INTO my_table(client_key ,client_value ,target) VALUES(?,?,?)";
final List< Entry<String,String> > list= getMapAsEntryList(bean.getClient());
int[] updateCounts = jdbcTemplate.batchUpdate(insert_query,
new BatchPreparedStatementSetter() {
public void setValues(PreparedStatement ps, int i) throws SQLException {
Entry<String,String> entry = list.get(i);
ps.setString(1, entry.getKey());
ps.setString(2, entry.getValue());
ps.setString(3, bean.getTarget());
}
public int getBatchSize() {
return list.size();
}
});
}
private List<Entry<String,String>> getMapAsEntryList(Map<String, String> client) {
List<Entry<String,String>> result=new ArrayList<Entry<String,String>>();
for(Entry<String,String> entry : client.entrySet())
{
result.add(entry);
}
return result;
}
}