Apex和Database相关知识点有哪些

118次阅读
没有评论

共计 15222 个字符,预计需要花费 39 分钟才能阅读完成。

本篇内容主要讲解“Apex 和 Database 相关知识点有哪些”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让丸趣 TV 小编来带大家学习“Apex 和 Database 相关知识点有哪些”吧!

salesforce.com 是世界上第一个提出云计算平台的公司, 同时, 它还引入了世界上第一门云计算编程语言 Apex。

1. Get Started with Apex

Learning Objectives

完成本单元后,您将能够:

描述 Apex 编程语言的主要功能。

保存一个 Apex 类并使用 Anonymous.Apex 调用方法。

使用开发者控制台检查调试日志。

Apex 的特点:

代码托管 - 在服务器 Lightning Platform 上保存,编译和执行 Apex。

Apex 是不区分大小写的语言

Apex 命名规范(这里我用的是 Java 的规范)

类名首字母大写,如果类名由多个单词组成,每个单词的首字母都要大写。如:

public class MyFirstClass{}

变量名、方法名首字母小写, 如果名称由多个单词组成,除第一个单词外,其他每个单词的首字母都要大写。如:

int index=0;
public void toString(){}

常量名全部大写

Apex 支持以下数据类型:

Primitive (Integer, Double, Long, Date, Datetime, String, ID, or Boolean) 原始数据类型(整数,双精度,长整型,日期,日期时间,字符串,ID 或布尔值)

Collections (Lists, Sets and Maps)

sObject

这是 Salesforce 中的特殊数据类型。

它类似于 SQL 中的表,并且包含与 SQL 中的列类似的字段。

有两种类型的 sObjects:Standard 和 Custom。

例如,Account 是一个标准的 sObject ; 任何其他用户定义的对象(如我们创建的 Customer 对象)是 Custom sObject。

Enums 枚举

Classes, Objects and Interfaces 类,对象和接口

Reference:

Apex 数据类型 -W3School

Trailhead Apex Practice https://trailhead.salesforce.com/content/learn/modules/apex_database/apex_database_intro

Create an Apex class with a method that returns an array (or list) of strings. Create an Apex class with a method that returns an array (or list) of formatted strings (Test 0 , Test 1 , …). The length of the array is determined by an integer parameter.

The Apex class must be called StringArrayTest and be in the public scope

The Apex class must have a public static method called generateStringArray

The generateStringArray method must return an array (or list) of strings

The method must accept an incoming Integer as a parameter, which will be used to determine the number of returned strings

The method must return a string value in the format Test n where n is the index of the current string in the array

/*
Apply To: Trailhead Apex Practice
Created On: 05-14-2021
Function: 
Developer Date Version Description
-------------------------------------------------
charles 05-14-2021 V1.0 Initial Version
//apex class
class StringArrayTest{
 //Apex method that takes in an Integer parameter and returns a List of Strings 
 public static void generateStringArray(Integer n){
 //Create a List of Strings
 List String  result = new List String  
 //Interate through a for loop to populate the array of Strings 
 for(Integer i=0; i  i++){ result.add( Test +i); 
 System.debug(result[i]); 
  return result; 
}

In the Developer Console, click Debug | Open Execute Anonymous Window.

In the window that opens, enter the following.

StringArrayTest.generateStringArray(5);

In the sample code above, you create an Apex class called StringArrayTest. You create a method called generateStringArray which takes in an Integer parameter and returns a List of Strings. If you fully understand the code above, then you should be able to complete this challenge with a breeze. However, if you re not too familar with the code above, I d recommend going through to the tutorial pages I linked above and read through to learn Apex first. I wish you best of luck and continue your journey to become Platform Dev Certified!

2. Use sObjects

Salesforce 中的每条记录 (行) 都在 Apex 中本地表示为 sObject。Salesforce 中的标准和自定义对象记录映射到 Apex 中的 sObject 类型。以下是 Apex 中用于标准对象的一些常见 sObject 类型名称。

Account

Contact

Lead

Opportunity

创建一个 sObject, 您需要声明一个变量, 并将其分配给一个 sObject 实例。变量的数据类型是 sObject 类型。以下示例创建一个类型为 Account 的 sObject 变量,并将其分配给名称为 charles 的新帐户。

Account acct = new Account(Name= charles

sObject 和字段名

对于自定义对象和自定义字段,API 名称始终以__c 后缀结尾。对于自定义关系型 (Relationship) 字段,API 名称以__r 后缀结尾。例如:

标签为 Merchandise 的自定义对象的 API 名称为 Merchandise__c。

标有 Description 标签的自定义字段的 API 名称为 Description__c。

标有 Items 标签的自定义关系型字段的 API 名称为 Items__r。

创建 sObjects 并添加字段

在插入 Salesforce 记录之前,必须首先在内存中将其创建为 sObject。与其他任何对象一样,sObject 是使用 new 运算符创建的:

ccount acct = new Account();

API 对象名称为 Apex 中 sObject 变量的数据类型。在此示例中,Account 是 acct 变量的数据类型。acct 变量引用的 Account 为空,因为我们尚未填充其任何字段。有两种添加字段的方法:通过构造函数或使用. 表示法。

添加字段的最快方法是在构造函数中将它们指定为“名称 / 值”对。例如,此语句创建一个新帐户 sObject,并使用字符串值填充其“名称”字段。

Account acct = new Account(Name= charles

Name 字段是帐户唯一必填的字段,这意味着必须先填充该字段,然后才能插入新记录。但是,您也可以为新记录填充其他字段。此示例还添加了电话号码和员工人数。

Account acct = new Account(Name= charles, Phone= (415)555-1212 , NumberOfEmployees=10000);

或者,您可以使用点表示法将字段添加到 sObject。以下内容与前面的示例等效,尽管它需要花费更多的代码行。

Account acct = new Account();
acct.Name =  charles 
acct.Phone =  (415)555-1212 
acct.NumberOfEmployees = 10000;

通常,在使用 sObjects 时,您使用特定的 sObject 数据类型,例如,标准对象使用 Account 或 Book 定制对象使用 Book__c。但是,当您不知道方法要处理的 sObject 类型时,可以使用通用的 sObject 数据类型。

使用通用 sObject 数据类型声明的变量可以引用任何 Salesforce 记录,无论是标准记录还是自定义对象记录。

这个例子显示了如何通用 sObject 变量可以分配给任何 Salesforce 对象: 一个名为 Book__c 的帐户和一个自定义对象。

sObject sobj1 = new Account(Name= Trailhead 
sObject sobj2 = new Book__c(Name= Workbook 1

相反,使用特定 sObject 数据类型声明的变量只能引用相同类型的 Salesforce 记录。

在处理通用 sObject 时,有时需要将 sObject 变量转换为特定的 sObject 类型。这样做的好处之一是能够使用点符号来访问字段,而点符号在通用 sObject 上不可用。由于 sObject 是所有特定 sObject 类型的父类型,因此可以将通用 sObject 强制转换为特定 sObject。本示例说明如何将通用 sObject 强制转换为 Account。

// Cast a generic sObject to an Account
Account acct = (Account)myGenericSObject;
// Now, you can use the dot notation to access fields on Account
String name = acct.Name;
String phone = acct.Phone;

3. Manipulate Records with DML

Learning Objectives

完成本单元后,您将能够:

使用 DML 插入,更新和删除记录。

批量执行 DML 语句。

使用 upsert 插入或更新记录。

捕获 DML 异常。

使用数据库方法插入带有部分成功选项的新记录并处理结果。

知道何时使用 DML 语句以及何时使用数据库方法。

对相关记录执行 DML 操作。

使用数据处理语言(缩写为 DML)在 Salesforce 中创建和修改记录。DML 通过提供简单的语句来插入,更新,合并,删除和还原记录,从而提供了一种直接的记录管理方法。

因为 Apex 是一种以数据为中心的语言,并且保存在 Lightning Platform 上,所以它可以直接访问 Salesforce 中的数据。与其他需要额外设置才能连接到数据源的编程语言不同,使用 Apex DML,管理记录变得非常容易!通过调用 DML 语句,您可以快速对 Salesforce 记录执行操作。

本示例将 charles 帐户添加到 Salesforce。首先创建一个帐户 sObject,然后将其作为参数传递给 insert 语句,该语句将记录保留在 Salesforce 中。

// Create the account sObject 
Account acct = new Account(Name =  charles ,Phone =  (415)555-1212 ,NumberOfEmployees=10000);
// Insert the account by using DML
insert acct;

DML 语句

以下 DML 语句可用。

insert

update

upsert

delete

undelete

merge

每个 DML 语句都接受单个 sObject 或一个 sObject 列表(或数组)。在 sObjects 列表上进行操作是一种处理记录的更有效方法。

除了几个语句外,所有这些语句都是熟悉的数据库操作。upsert 和 merge 语句特定于 Salesforce,并且非常方便。

upsert DML 操作使用指定的字段来确定是否存在现有对象,如果没有指定字段,则使用 ID 字段在单个语句中创建新记录并更新 sObject 记录。

除了几个语句外,所有这些语句都是熟悉的数据库操作。upsert 和 merge 语句特定于 Salesforce,并且非常方便。

merge 语句将多达三个相同 sObject 类型的记录合并到其中一个记录中,删除其他记录,并重新关联任何相关记录。

ID 字段自动分配给新记录

插入记录时,系统会为每个记录分配一个 ID。除了将 ID 值保留在数据库中之外,ID 值还将自动填充到在 DML 调用中用作参数的 sObject 变量上。

本示例说明如何获取与插入帐户相对应的 sObject 上的 ID。

/*
 * Apply To: DML Practice
 * Created On: 05-15-2021
 * Developer Date Version Description
 * -------------------------------------------------
 * charles 05-15-2021 V1.0 Initial Version
 */
public class DMLPractice1 { public static void testDML(){
 //Create the account sObject 
 Account acct = new Account(Name= charles,Phone =  (415)555-1212 ,NumberOfEmployees=100); 
 Insert acct; 
 //Get the new ID on the inserted sObject argument
 ID acctID = acct.Id; 
 System.debug(ID= +acctID); 
 //Debug log result(the ID will be different in your case)
 }
}

Beyond the Basics

因为示例中的 sObject 变量在 DML 调用之后包含 ID,所以您可以重用此 sObject 变量以执行进一步的 DML 操作,例如更新,因为系统将能够通过匹配 ID 将 sObject 变量映射到其对应的记录。您可以从数据库中检索记录以获取其字段,包括 ID 字段,但是 DML 无法做到这一点。您需要使用 SOQL 编写查询。您将在另一个单元中学习 SOQL。

批量 DML

您可以在单个 sObject 上执行批量 DML 操作,也可以在 sObject 列表上批量执行 DML 操作。建议执行批量 DML 操作,因为这有助于避免达到调控器限制,例如,每个 Apex 事务的 DML 限制为 150 条语句。设置此限制是为了确保公平访问 Lightning Platform 中的共享资源。在 sObject 列表上执行 DML 操作被视为一个 DML 语句,而不是每个 sObject 的一个语句。

DML Practice1

Create a method for inserting accounts. To pass this challenge, create an Apex class that inserts a new account named after an incoming parameter. If the account is successfully inserted, the method should return the account record. If a DML exception occurs, the method should return null.

The Apex class must be called AccountHandler and be in the public scope

The Apex class must have a public static method called insertNewAccount

The method must accept an incoming string as a parameter, which will be used to create the Account name

The method must insert the account into the system and then return the record

The method must also accept an empty string, catch the failed DML and then return null

/*
 * Apply To: DML Practice
 * Created On: 05-15-2021
 *
 * Developer Date Version Description
 * -------------------------------------------------
 * charles 05-15-2021 V1.0 Initial Version
 * 
 */
public class AccountHandler { public static Account insertNewAccount(String accountName){ Account acct = new Account(Name = accountName);
 try { 
 insert acct; 
 }catch(DmlException e){ System.debug( A DML exception has occurred:  +e.getMessage()); 
  return null; 
 }
 return acct; 
 }
}

如果发现问题或有更好的方法欢迎交流讨论。

DML Practice2

Create a class and one method that creates a specified number of new accounts and adds them to the database. Create a public Apex class named AccountHandler

Add a public static method to the class:

Name: insertAccount

Include a parameter for the number of new accounts:

Data type: Integer

Create a list of Account records:

List name: addAccounts

Use a while loop to add n new Accounts to the list, where n is a value that is incremented by 1 during each iteration of the loop:

Name: Acme Inc n

AccountNumber: A000n

Hint: You did something like this when you created three new Tea Factory stores. Write one DML statement that inserts all the records into the database at one time Run your insertAccount method

/*
 * Apply To: DML Practice
 * Created On: 05-20-2021
 * 
 * Developer Date Version Description
 * -------------------------------------------------
 * charles 05-20-2021 V1.0 Initial Version
 * 
 */
public class AccountHandler { public static void insertAccount(Integer n){
 List Account  addAccounts = new List Account  
 for(Integer i = 0; i  i++){ Account acct = new Account(); 
  acct.Name =  Acme In  
 acct.AccountNumber =  A000  
  addAccounts.add(acct); 
 }
 try{
 insert addAccounts; 
 }catch(DMLException e){ System.debug( A DML Exception has occurred +e.getMessage()); 
 }
 }
}

在匿名窗口中执行下面的代码:

AccountHandler.insertAccount(10);

效果演示:

执行上述代码前: 我的 Acounts 下面只有 3 条记录

执行上述代码后: 我的 Accounts 下面多了 10 条记录
结果 Trailhead 报错了,我才知道理解错了,我以为 Acme Inc n 的意思是 Acme Inc 1 , Acme Inc 2 , Acme Inc 3….

改正后的做法:

/*
 * Apply To: DML Practice
 * Created On: 05-20-2021
 * 
 * Developer Date Version Description
 * -------------------------------------------------
 * charles 05-20-2021 V2.0 Initial Version
 * 
 */
public class AccountHandler { public static void insertAccount(Integer n){
 List Account  addAccounts = new List Account  
 for(Integer i = 0; i  i++){ Account acct = new Account(); 
  acct.Name =  Acme Inc  
 acct.AccountNumber =  A000  
  addAccounts.add(acct); 
 }
 try{
 insert addAccounts; 
 }catch(DMLException e){ System.debug( A DML Exception has occurred +e.getMessage()); 
 }
 }
}

效果演示:成功在 Accounts 上插入了 10 条数据

4. Write SOQL Queries

Learning Objectives

在 Apex 中编写 SOQL 查询。

通过使用开发人员控制台中的查询编辑器执行 SOQL 查询。

通过使用匿名 Apex 执行嵌入在 Apex 中的 SOQL 查询。

查询相关记录。

Reference

Use sObjects and DML Learning Objectives

编写 SOQL 查询

要从 Salesforce 中读取记录,您必须编写查询。Salesforce 提供了 Salesforce 对象查询语言(简称 SOQL),可用于读取保存的记录。SOQL 与标准 SQL 语言类似,但是为 Lightning Platform 定制的。

由于 Apex 可以直接访问存储在数据库中的 Salesforce 记录,因此您可以将 SOQL 查询嵌入到 Apex 代码中,并以简单的方式获取结果。当 SOQL 嵌入 Apex 中时,称为内联 SOQL。

要将 SOQL 查询包含在 Apex 代码中,请将 SOQL 语句包装在方括号 [] 中,然后将返回值分配给 sObjects 数组。例如,以下内容检索具有两个字段 Name 和 Phone 的所有帐户记录,并返回一个 Account sObjects 数组。

Account [ ] acct = [select Name,Phone from Account];

预备知识

本单元中的某些查询期望组织拥有客户和联系人。在运行查询之前,请创建一些示例数据。

在开发人员控制台

在窗口中插入以下代码片段, 然后单击执行。

/*
 * Apply To: SOQL Practice
 * Created On: 05-16-2021
 * 
 * Developer Date Version Description
 * -------------------------------------------------
 * charles 05-16-2021 V1.0 Initial Version
 * 
 */
public class SOQLPractice1 { public static void testSOQL(){
 // Add account and related contact
 Account acct = new Account(
 Name= SFDC Computing ,
 Phone= (415)555-1212 ,
 NumberOfEmployees=50,
 BillingCity= San Francisco 
 insert acct;
 // Once the account is inserted, the sObject will be 
 // populated with an ID.
 // Get this ID.
 ID acctID = acct.ID;
 // Add a contact to this account.
 Contact con = new Contact(
 FirstName= Carol ,
 LastName= Ruiz ,
 Phone= (415)555-1212 ,
 Department= Wingo ,
 AccountId=acctID);
 insert con;
 // Add account with no contact
 Account acct2 = new Account(
 Name= The SFDC Query Man ,
 Phone= (310)555-1213 ,
 NumberOfEmployees=50,
 BillingCity= Los Angeles ,
 Description= Expert in wing technologies. 
 insert acct2;
 
 }
}

扩展

与其他 SQL 语言不同,您不能使用 * 来查询 所有记录。您必须指定要显式获取的每个字段。如果您尝试访问未在 SELECT 子句中指定的字段,则会收到错误消息,因为尚未检索到该字段。

您无需在查询中指定 Id 字段,因为无论在查询中是否指定,它始终会在 Apex 查询中返回。例如:SELECT Id,Phone FROM Account 和 SELECT Phone FROM Account 是等效的语句。如果您要检索的是唯一字段,则可能只有一次需要指定 ID 字段,因为您必须至少列出一个字段:SELECT Id FROM Account。在查询编辑器中运行查询时,您可能还需要指定 ID 字段,因为除非指定,否则不会显示 ID 字段。

在 SOQL 查询中访问变量

如果 Apex 中的 SOQL 语句前面带有冒号(:),则它们可以引用 Apex 代码变量和表达式。在 SOQL 语句中使用局部变量称为 bind。

本示例说明了如何使用 targetDeparment WHERE 子句中的变量。

String targetDepartment =  Wingo 
Contact[] techContacts = [SELECT FirstName,LastName 
 FROM Contact WHERE Department=:targetDepartment];

SOQL Practice

Create an Apex class that returns contacts based on incoming parameters. For this challenge, you will need to create a class that has a method accepting two strings. The method searches for contacts that have a last name matching the first string and a mailing postal code matching the second. It gets the ID and Name of those contacts and returns them.

The Apex class must be called ContactSearch and be in the public scope

The Apex class must have a public static method called searchForContacts

The method must accept two incoming strings as parameters

The method should then find any contact that has a last name matching the first string, and mailing postal code (API name: MailingPostalCode) matching the second string

The method should finally return a list of Contact records of type List that includes the ID and Name fields

/*
 * Apply To: SOQL Practice
 * Created On: 05-16-2021
 * 
 * Developer Date Version Description
 * -------------------------------------------------
 * charles 05-16-2021 V1.0 Initial Version
 * 
 */
public class ContactSearch { public static List Contact  searchForContacts(String parm1,String parm2){  List Contact  contactList = [select ID,Name from Contact where( LastName =: parm1 AND MailingPostalCode =: parm2)]; 
 return contactList; 
 }
}

4. Write SOSL Queries

Learning Objectives

描述 SOSL 和 SOQL 之间的区别。

使用 SOSL 查询跨多个对象搜索字段。

通过使用开发人员控制台中的查询编辑器执行 SOSL 查询。

编写 SOSL 查询 Salesforce 对象搜索语言(SOSL)是一种 Salesforce 搜索语言,用于在记录中执行文本搜索。使用 SOSL 在 Salesforce 中跨多个标准和自定义对象记录搜索字段。SOSL 与 Apache Lucene 相似。将 SOSL 查询添加到 Apex 很简单 - 您可以将 SOSL 查询直接嵌入到 Apex 代码中。当 SOSL 嵌入 Apex 中时,称为内联 SOSL。

6. Salesforce Developer Console Shortcut Key

Ctrl+. : 表示代码自动补全功能

Ctrl+D : 表示删除光标所在的行

Ctrl+Alt+N : 将光标放在一条语句上,然后点击右上角的’Go To’就会跳到相应的语句中

Shift+Tab : 表示格式化选中的代码

7.Define Sets and Maps

Learning Objectives

After completing this unit, you’ll be able to:

Create sets and maps.

Describe how lists, sets, and maps differ.

Decide when to use a set instead of a list.

如您所知,列表是具有相同数据类型的项目的有序集合。每个项目都有一个称为索引的位置。这使按编号索引检索列表中的项目变得容易。但是 Apex 的收藏不仅仅是列表。集合的其他两种类型是集合和映射。

Set

到目前为止,您已经创建了一种 Collection 类型,列表。set 集合是相同类型的无序唯一项集合。与 List 列表类似,Set 集合是一组称为元素的项,所有元素都具有相同的数据类型,如字符串、整数甚至 Account。与 List 列表不同,集合不维护其元素的特定顺序。因为元素是无序的,所以 Set 集合不能有任何重复。如果你试图添加一个已经在 Set 集合中的元素,你不会得到一个错误,但是新值不会添加到 Set 集合中。
请记住,在循环遍历 List 列表时,总是按照添加到 List 列表中的项的顺序访问它的项。当循环遍历一个 Set 集合时,因为元素是无序的,所以可以以随机顺序访问元素。

/*
 * Apply To: Set Practice
 * Created On: 05-20-2021
 * 
 * Developer Date Version Description
 * -------------------------------------------------
 * charles 05-20-2021 V1.0 Initial Version
 * 
 */
public class SetPractice { public static void testSet(){
 Set String  teaTypes = new Set String  
 teaTypes.add( Black  
 teaTypes.add( White  
 teaTypes.add( Herbal  
 System.debug(teaTypes); 
 }
}

匿名窗口执行:

SetPractice.testSet();

Map

与 List 列表或 Set 集合相比,Map 是更复杂的集合。映射中的每个项目都有两个部分:键和值,称为键值对。键和值可以是任何数据类型。尽管每个键都是唯一的,但是值可以在映射中重复。想象一下电话国家代码的映射。国家 / 地区代码是键,国家 / 地区名称是值。每个国家 / 地区代码都是唯一的,但是国家 / 地区可以重复(因为一个国家 / 地区可能包含多个国家 / 地区代码)。

put 方法

要将键值对添加到 Map,请使用 put 方法,如下所示:

put 方法需要两个参数:键和值。让我们创建一个茶类型(键)及其风味特征(值)的映射。

Tea Types and Flavor Profiles

Create a Map

/*
 * Apply To: Map Practice
 * Created On: 05-20-2021
 * 
 * Developer Date Version Description
 * -------------------------------------------------
 * charles 05-20-2021 V1.0 Initial Version
 * 
 */
public class Tea { public static void orderTea(){
 Map String,String  teaTypes = new Map String,String  
 teaTypes.put( Black , Earthy  
 teaTypes.put( White , Sweet  
 teaTypes.put( herbal , Sweet  
 System.debug(teaTypes); 
 } 
}

重点

List 代表一类的有序数据列表。数据序号从 0 开始。与 JAVA 不同的是:List 是一个类,并且不存在 ArrayList 等子类。即实例化

eg:List String  list1 = new List String

List 可以通过自身构造函数实例化,也可以通过数组进行实例化。

以下为 List 主要方法:
注:set()方法在设置插入位置以前应确保长度大于需要插入的位置,否则将抛出异常。

Set 代表一类数据的无序列表。与 JAVA 不同的是:Set 是一个类,不存在 HashSet 等子类。即实例化

eg:Set String  set1 = new Set String

到此,相信大家对“Apex 和 Database 相关知识点有哪些”有了更深的了解,不妨来实际操作一番吧!这里是丸趣 TV 网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-08-25发表,共计15222字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)