salesforce零基礎學習(一百一十一)custom metadata type數據獲取方式更新 salesforce 零基礎學習(四十)Custom Settings簡單使用

本篇參考:

https://developer.salesforce.com/docs/atlas.en-us.234.0.apexref.meta/apexref/apex_methods_system_custom_metadata_types.htm

https://trailhead.salesforce.com/en/content/learn/modules/platform-developer-i-certification-maintenance-winter-22/learn-whats-new-for-platform-developers-22

我們都知道salesforce裏面 custom setting的使用方法,不瞭解的小夥伴可以開啓時空門:salesforce 零基礎學習(四十)Custom Settings簡單使用

custom setting好用是好用,但是理解起來可以理解成特殊的表,數據還是要維護的,所以針對不同的sandbox或者生產環境,可能會有一些 manual action來維護數據或者初期的導入。所以針對 list類型的 custom setting,官方更建議使用 custom metadata type來維護。我們可以通過metadata的方式來部署這些內容,這樣可以盡最大的可能去減少因爲遺漏導致的數據不完整從而導致業務處理有問題的情況。

那我們之前在使用 custom metadata type特別煩人的地方是,我們需要通過搜索數據的方式來獲取數據,使用方式很類似我們object的query。比如下面的demo

System.debug(LoggingLevel.INFO, '*** Limits.getQueryRows(): ' + Limits.getQueryRows());
Country_Code__mdt countryCode = [
  SELECT Id, MasterLabel, Country_Code__c
  FROM Country_Code__mdt
  WHERE MasterLabel = 'Canada'
  LIMIT 1
];
System.debug(LoggingLevel.INFO, '***after Limits.getQueryRows(): ' + Limits.getQueryRows());

使用這種方式是需要消耗SOQL的查詢數量的,所以我們在實際使用時,偶爾還是會考慮取捨,使用 list custom setting而不是 custom metadat type。

 針對新的release出來以後,custom metadata同樣也支持了類似 custom setting的查詢方式,這種既不計算了SOQL的查詢數,也使得結果獲取更快。方法提供了getInstance以及 getAll,demo中我們使用getInstance()方法,感興趣的小夥伴可以查看一下上面鏈接的其他的方法。

System.debug(LoggingLevel.INFO, '*** Limits.getQueryRows(): ' + Limits.getQueryRows());
// Country_Code__mdt countryCode = [
//   SELECT Id, MasterLabel, Country_Code__c
//   FROM Country_Code__mdt
//   WHERE MasterLabel = 'Canada'
//   LIMIT 1
// ];
Country_Code__mdt countryCode = Country_Code__mdt.getInstance('Canada');
System.debug(LoggingLevel.INFO, '***after Limits.getQueryRows(): ' + Limits.getQueryRows());

使用getInstance方法以後的執行結果

注意點:當前的這個getInstance方法是基於spring21的更新,對應的API version爲API 51,所以如果apex中如果使用此功能,一定要記得version設置爲51及以上,否則會報錯。

總結:篇中簡單的介紹了一下 custom metadata type的新取法,對於代碼中深受 limitation所頭疼的小夥伴可以考慮去進行性能調優了。當然,salesforce每一期的release都驚喜不斷,大家也要多關注關注 release note哦,有用的內容找機會可以慢慢的更新一下用法。篇中有錯誤地方歡迎指出,有不懂歡迎留言。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章