JDBC has a feature of group multiple queries in one single unit and pass it in a single network trip to the database.
As shown in this code example:
String[] EMPLOYEES = new String[]{"Zuck","Mike","Larry","Musk","Steve"}; String[] DESIGNATIONS = new String[]{"CFO","CSO","CTO","CEO","CMO"}; String insertEmployeeSQL = "INSERT INTO EMPLOYEE(ID, NAME, DESIGNATION) VALUES (?,?,?)"; PreparedStatement employeeStmt = connection.prepareStatement(insertEmployeeSQL); for(int i = 0; i < EMPLOYEES.length; i++){ String employeeId = UUID.randomUUID().toString(); employeeStmt.setString(1,employeeId); employeeStmt.setString(2,EMPLOYEES[i]); employeeStmt.setString(3,DESIGNATIONS[i]); employeeStmt.addBatch(); } employeeStmt.executeBatch(); But, with SQL we have the feature of using INSERTs with many VALUES groups, just like at:
String[] EMPLOYEES = new String[] {"Zuck","Mike","Larry","Musk","Steve"}; String[] DESIGNATIONS = new String[] {"CFO","CSO","CTO","CEO","CMO"}; StringBuilder insertEmployeeSQL = "INSERT INTO EMPLOYEE(ID, NAME, DESIGNATION) VALUES (?,?,?)" + ", (?, ?, ?)".repeat(EMPLOYEES.length - 1); PreparedStatement employeeStmt = connection.prepareStatement(insertEmployeeSQL.toString()); int columnIndex = 0; for(int i = 0; i < EMPLOYEES.length; i++){ String employeeId = UUID.randomUUID().toString(); employeeStmt.setString(++columnIndex, employeeId); employeeStmt.setString(++columnIndex, EMPLOYEES[i]); employeeStmt.setString(++columnIndex, DESIGNATIONS[i]); } employeeStmt.execute(); What I need to know is, what is the difference between these two approaches?
Obs:
The first example is from here https://www.baeldung.com/jdbc-batch-processing and the second edited by me. English is not my native language and this is my first post so sorry for anything.