Search code examples
javaspringspring-jdbc

jdbcTemplate.batchUpdate not aplicable error


public void insert(List<Student> students) {
    String sql = "INSERT INTO sqlDB.Student VALUES(?,?,?)";
    ArrayList<Object[]> sqlargs = new ArrayList<Object[]>();
    for(Student tempstudent : students) {
        Object[] studentData = {tempstudent.getRollNo(),tempstudent.getName(),tempstudent.getAddress()};
        sqlargs.add(studentData);
    }
    jdbcTemplate.batchUpdate(sql, sqlargs);
    System.out.println("Batch Update Completed-->");
}

Error:

log4j:WARN No appenders could be found for logger (org.springframework.context.support.ClassPathXmlApplicationContext).
log4j:WARN Please initialize the log4j system properly.
ApplicationContext is Loaded
Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
    The method batchUpdate(String, BatchPreparedStatementSetter) in the type JdbcTemplate is not applicable for the arguments (String, ArrayList<Object[]>)

    at com.jdbc.dao.StudentDAOimpl.insert(StudentDAOimpl.java:76)
    at com.jdbc.service.StudentDAOHelper.setUpStudentTable(StudentDAOHelper.java:35)
    at com.jdbc.test.Runner.main(Runner.java:21)

I was trying to insert a batch of student data into the database using jdbcTemplate.batchUpdate(). Above is my method and also the error that I'm getting. As of now I only learned about Spring and JDBC. Is there any other way of using batchupdate interface?


Solution

  • public void batchInsert(final List<Student> students) {
        
        String sql ="INSERT INTO sqlDB.Student VALUES(?,?,?)";
        
        jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
    
            public void setValues(PreparedStatement ps, int i) throws SQLException {
                
                Student student=students.get(i);
                
                ps.setInt(1, student.getRollNo());
                ps.setString(2, student.getName());
                ps.setNString(3, student.getAddress());
            }
    
            public int getBatchSize() {
                // TODO Auto-generated method stub
                return students.size();
            }
            
            
        });
        
    }