Dưới đây là 10 bài tập giúp bạn làm quen dần với Batch Apex trong Salesforce. Mỗi bài có mô tả yêu cầu, gợi ý về start, execute, finish và cách chạy batch.
Mục tiêu: Làm quen với batch cơ bản.
start: QuerySELECT Id, Name FROM Accountexecute:System.debug(Name)finish: In ra"Hoàn thành batch in Account"
Mục tiêu: Batch update dữ liệu.
start: QuerySELECT Id, Phone FROM Contact WHERE Phone = nullexecute: GánPhone = '000-000'vàupdatefinish: Log"Đã update xong Contact thiếu Phone"
Mục tiêu: Batch delete.
start: QuerySELECT Id FROM Lead WHERE Status = 'Closed - Not Converted'execute:delete scopefinish: Log"Đã xóa xong Lead Closed - Not Converted"
Mục tiêu: Sử dụng Database.Stateful để lưu biến đếm.
start: QuerySELECT Id, StageName FROM Opportunityexecute: Dùng Map<String, Integer>để đếm theo Stagefinish:System.debug(map kết quả)
Mục tiêu: Update có điều kiện.
start: QuerySELECT Id, Industry FROM Account WHERE Industry = nullexecute: UpdateIndustry = 'Technology'finish: Debug tổng số record đã update
Mục tiêu: Dùng logic trong finish.
start: QueryAccountexecute: Không cần xử lý phức tạpfinish: TạoMessaging.SingleEmailMessagevà gửi đến admin
Mục tiêu: Batch xử lý liên quan giữa nhiều object.
start: QuerySELECT Id, (SELECT Id FROM Contacts) FROM Accountexecute: Đếm số Contact và update fieldfinish: Log"Hoàn thành cập nhật số lượng Contact"
Mục tiêu: Hiểu batch size ảnh hưởng thế nào.
start: QueryAccountexecute: Debug"Scope size: " + scope.size()- Khi chạy thử: Thay batch size
10,200,2000để quan sát log
Mục tiêu: Truy vấn > 50.000 record.
start: DùngDatabase.getQueryLocator('SELECT Id FROM Account')execute: Debug Idfinish: Log"Xử lý dữ liệu lớn xong"
Mục tiêu: Sử dụng Database.Stateful và chaining.
start: QueryAccountexecute: Update hoặc debugfinish: GọiDatabase.executeBatch(new AnotherBatchClass())để chạy tiếp batch khác
Tạo file Anonymous Apex và chạy trong VSCode hoặc Developer Console:
BatchTemplate myBatch = new BatchTemplate();
Database.executeBatch(myBatch, 200);