JdbcTemplate.batchUpdate in Spring
November 07, 2013
Batch update in spring can be achieved by JdbcTemplate. JdbcTemplate has a method as JdbcTemplate.batchUpdate which takes input of sql query and the object of BatchPreparedStatementSetter. BatchPreparedStatementSetter has to override two methods setValues and getBatchSize. In our example we have a farmar table and we will do batch update.
FarmarDao.java
package com.concretepage.dao; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.List; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.BatchPreparedStatementSetter; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; import com.concretepage.bean.Farmar; @Repository public class FarmarDao { private JdbcTemplate jdbcTemplate; @Autowired public void setDataSource(DataSource dataSource) { this.jdbcTemplate = new JdbcTemplate(dataSource); } public int[] farmarBatchUpdate(final List<Farmar> farmars) { int[] updateCnt = jdbcTemplate.batchUpdate( "update farmar set status= ? where age = ?", new BatchPreparedStatementSetter() { public void setValues(PreparedStatement ps, int i) throws SQLException { ps.setString(1,farmars.get(i).getStatus()); ps.setInt(2,farmars.get(i).getAge()); } public int getBatchSize() { return farmars.size(); } } ); return updateCnt; } }
SpringTest.java
package com.concretepage; import java.util.ArrayList; import java.util.List; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.concretepage.bean.Farmar; import com.concretepage.dao.FarmarDao; public class SpringTest { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml"); FarmarDao farmarDao = (FarmarDao)context.getBean("farmarDao"); Farmar f1 = new Farmar("Ram", 20, "active"); Farmar f2 = new Farmar("Shyam", 25, "active"); List<Farmar> list = new ArrayList<Farmar>(); list.add(f1); list.add(f2); int[] cnt = farmarDao.farmarBatchUpdate(list); System.out.println("Update count : "+cnt.length); } }
package com.concretepage.bean; public class Farmar { private String name; private int age; private String status; public Farmar(String name, int age, String status){ this.name = name; this.age = age; this.status = status; } public String getName() { return name; } public int getAge() { return age; } public String getStatus() { return status; } }
jdbctemplate-batchupdate-in-spring.zip