Wednesday, December 13, 2023

Bulk data insert using prepared statement

     public Optional<List<UUID>> addInBatch(List<ApiActionLogs> apiActionLogs) {
        
        if (apiActionLogs == null || apiActionLogs.isEmpty()) {
            return Optional.ofNullable(Collections.emptyList());
        }
        List<UUID> insertedUUIDList = new ArrayList<>();
        ByteArrayToUUIDConverter byteArrayToUUIDConverter = new ByteArrayToUUIDConverter();
        try (Connection connection = ConnectionUtil.getWriteConnection()) {
            connection.setAutoCommit(false);
            String sql = String.format(
                    "INSERT INTO %s (uuid, agency_id, user_id, `action`, api_bulk_action_queues_uuid, message_log, "
                    + "status, response_code, request_data, created_at, updated_at) "
                    + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", "api_action_logs ");
            
            try (PreparedStatement statement = connection.prepareStatement(sql,                                  Statement.RETURN_GENERATED_KEYS)) {
                int counter = 0;
                int batchSize = 100;
                List<UUID> batchRequests = new ArrayList<>();
                
                for (ApiActionLogs apiActionLog : apiActionLogs) {
                    if (apiActionLog == null
                            || apiActionLog.getAgencyId() == null
                            || apiActionLog.getUserId() == null
                            || apiActionLog.getApiBulkActionQueuesUuid() == null) {
                        continue;
                    }
                    statement.clearParameters();
                    apiActionLog.setUuid(UUID.randomUUID());
                    
                    statement.setBytes(1, byteArrayToUUIDConverter.to(apiActionLog.getUuid()));
                    statement.setString(2, apiActionLog.getAgencyId().toString());
                    statement.setString(3, apiActionLog.getUserId().toString());
                    statement.setString(4, apiActionLog.getAction() == null ? null : apiActionLog.getAction().name());
                    statement.setBytes(5,  byteArrayToUUIDConverter.to(apiActionLog.getApiBulkActionQueuesUuid()));
                    statement.setString(6, apiActionLog.getMessageLog());
                    statement.setString(7, apiActionLog.getStatus() == null ? null : apiActionLog.getStatus().name());
                    statement.setString(8, apiActionLog.getResponseCode());
                    statement.setString(9, apiActionLog.getRequestData() == null ? null : apiActionLog.getRequestData().toString());
                    statement.setTimestamp(10, Timestamp.valueOf(LocalDateTime.now()));
                    statement.setTimestamp(11, Timestamp.valueOf(LocalDateTime.now()));
                    
                    statement.addBatch();
                    
                    batchRequests.add(apiActionLog.getUuid());
                    
                    if ((counter + 1) % batchSize == 0 || (counter + 1) == apiActionLogs.size()) {
                        try {
                            statement.executeBatch(); // Execute Batch Operations
                            insertedUUIDList.addAll(batchRequests);
                            batchRequests.clear();
                        } catch (Exception e) {
                            log.error("Error :{}", e);
                            System.out.println("Error "+e);
                            if (!connection.isClosed()) {
                                connection.rollback();
                            }
                            batchRequests.clear();
                        }
                        
                        statement.clearBatch();
                    }
                    
                    counter++;
                }
            } catch (Exception e) {
                log.error("Error :{}", e);
                System.out.println("Error2 "+e);
                e.printStackTrace();
            }

            connection.commit(); // execute prepare statement
            
            if(!insertedUUIDList.isEmpty()) {
                
                return Optional.ofNullable(insertedUUIDList);
            }
            
        } catch (Exception e) {
            log.error("Error :{}", e);
            System.out.println("Error3 "+e);
            e.printStackTrace();
        }

        return Optional.ofNullable(Collections.emptyList());
    }

No comments:

Post a Comment

Abstract factory pattern

When single task can be done by multiple groups/family of objects and decision is taken at the runtime.