Spring jdbcTemplate.batchUpdate example


      Click here to attend Spring Framework 4.x and certification course with a discount


package nl.kameroom.urllogservice;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import javax.sql.DataSource;

import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;

public class UrlLogService {
	
	private JdbcTemplate jdbcTemplate;
	private boolean enabled = false;

    public void setDataSource(DataSource dataSource) {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }

    public UrlLogService(boolean isEnabled) {
    	enabled = isEnabled;
    	
    }
    public void log(final List<String> urls) {
    	
    	if(enabled) {
	    	final String INSERT_SQL = "INSERT INTO `kameroom`.`urllog` (url) "
					+ "VALUES (?)";
	    	try {
	    		jdbcTemplate.batchUpdate(INSERT_SQL, new BatchPreparedStatementSetter() {					
					@Override
					public void setValues(PreparedStatement ps, int i) throws SQLException {
						String url = urls.get(i);
						ps.setString(1, url);						
					}					
					@Override
					public int getBatchSize() {
						return urls.size();
					}
				});
			} catch (Exception e) {
				e.printStackTrace();
			}
    	}    	
    }
    public void logRow(final String url,final String user,final String IP) {

    	if(enabled) {
	    	final String INSERT_SQL = "INSERT INTO `kameroom`.`urllog` (url,user,ip) "
					+ "VALUES (?,?,?)";
	    	try {
	    		jdbcTemplate.update(new PreparedStatementCreator() {
					public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
						PreparedStatement ps = connection.prepareStatement(INSERT_SQL);
						ps.setString(1, url);
						ps.setString(2, user);
						ps.setString(3, IP);
						return ps;
					}
				});	
			} catch (Exception e) {
				e.printStackTrace();
			}
    	}
    	
    }
    
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s