Book Image

SPRING COOKBOOK

Book Image

SPRING COOKBOOK

Overview of this book

Table of Contents (19 chapters)
Spring Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Saving a list of objects at once


In this recipe, we will add a DAO method to save a list of objects to the database efficiently.

How to do it…

Use the batchUpdate() method that takes an SQL insert query and a list of values as parameters:

public void add(List<User> userList) {
  String sql = "insert into user (first_name, age) values (?, ?)";
  
  List<Object[]> userRows = new ArrayList<Object[]>();
  for (User user : userList) {
        userRows.add(new Object[] {user.getFirstName(), user.getAge()});
  }
  
   jdbcTemplate.batchUpdate(sql, userRows);
}

How it works…

A list of SQL insert queries will be generated from the SQL insert query string and the list of values. They will be sent to the database and committed all at once.