Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set batch size in spring JDBC batch update

How do I set batch size in spring JDBC batch update to improve performance? Listed below is my code snippet.

public void insertListOfPojos(final List<Student> myPojoList) {

    String sql = "INSERT INTO " + "Student " + "(age,name) " + "VALUES "
            + "(?,?)";
    try {
        jdbcTemplateObject.batchUpdate(sql,
                new BatchPreparedStatementSetter() {

                    @Override
                    public void setValues(PreparedStatement ps, int i)
                            throws SQLException {

                        Student myPojo = myPojoList.get(i);
                        ps.setString(2, myPojo.getName());
                        ps.setInt(1, myPojo.getAge());

                    }

                    @Override
                    public int getBatchSize() {
                        return myPojoList.size();
                    }
                });
    } catch (Exception e) {
        System.out.println("Exception");
    }
}

I read that with Hibernate you can provide your batch size in the configuration xml. For example, <property name="hibernate.jdbc.batch_size" value="100"/>. Is there something similar in Spring's jdbc?

like image 746
user1454829 Avatar asked Dec 31 '25 04:12

user1454829


1 Answers

There is no option for jdbc that looks like Hibernate; I think you have to get a look to specif RDBMS vendor driver options when preparing connection string.

About your code you have to use

BatchPreparedStatementSetter.getBatchSize()

or

JdbcTemplate.batchUpdate(String sql, final Collection<T> batchArgs, final int batchSize, final ParameterizedPreparedStatementSetter<T> pss)

like image 100
Luca Basso Ricci Avatar answered Jan 03 '26 07:01

Luca Basso Ricci



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!