我需要一个从用户接收数据的触发器(批量加载大约1000条记录)并将它们存储在Salesforce数据库中。问题是用户可以在Trigger.new
或甚至不同的批次中多次出现。自定义对象名称为CBK_User
,并且EXTERNAL_ID
(唯一)名为USER_ID
。在我的代码中,我检查数据库中是否存在用户:
Map<String, CBK_User__c> users = new Map<String,CBK_User__c>
([select Id, USER_ID__c from CBK_User__c where USER_ID__c in : userIds]);
(userIds具有Trigger.new对象的外部ID)
当我尝试插入时,它会给我错误:
DUPLICATE_VALUE, duplicate value found: USER_ID__c duplicates value on
record with id: a1QJ0000000HRd8"
如何防止批量插入重复值?
答案 0 :(得分:3)
我已将您的问题改编为this basic example(练习2:防范重复)
您应首先清除重复条目中的“新”列表,然后从db中的现有清除。
trigger CBK_UserDuplicatePreventer on CBK_User__c (before insert, before update) {
//Enter a map declaration to hold records which we will add,
// this will become a unique map, no duplicate values within it.
Map<String, CBK_User__c> cbkUserMap = new Map<String, CBK_User__c>();
//The next few lines loop across the array of records that are passed into
//the trigger in bulk fashion from any API or User Interface database operation.
//The goal of this loop is to ensure that there are no duplicates within
//the batch that we have received and to gather a list of externalIds that we will use later
for (CBK_User__c cbkUser : System.Trigger.new) {
/* Make sure we don't treat an externalId that
isn't changing during an update as a duplicate. */
if ((cbkUser.USER_ID__c != null) && (System.Trigger.isInsert ||
(cbkUser.USER_ID__c != System.Trigger.oldMap.get(cbkUser.Id).USER_ID__c))) {
// Make sure another new CBK_User__c isn't also a duplicate
if (cbkUserMap.containsKey(cbkUser.USER_ID__c)) {
cbkUser.USER_ID__c.addError('Another new CBK_User__c has the same USER_ID.');
} else {
cbkUserMap.put(cbkUser.USER_ID__c, cbkUser);
}
}
}
// Using a single database query, find all the CBK_User__c in
// the database that have the same USER_ID as ANY
// of the CBK_User__c being inserted or updated. */
for (CBK_User__c cbkUser : [SELECT USER_ID__c FROM CBK_User__c WHERE USER_ID__c IN :cbkUserMap.KeySet()]) {
CBK_User__c newCbkUser = cbkUserMap.get(cbkUser.USER_ID__c);
newCbkUser.USER_ID__c.addError('A CBK_User__c with this USER_ID already exists.');
}
}