Apex和Database相关知识点有哪些

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

汉寿网站制作公司哪家好,找成都创新互联!从网页设计、网站建设、微信开发、APP开发、响应式网站建设等网站项目制作,到程序开发,运营维护。成都创新互联从2013年开始到现在10年的时间,我们拥有了丰富的建站经验和运维经验,来保证我们的工作的顺利进行。专注于网站建设就选成都创新互联

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

1. Get Started with Apex

Learning Objectives

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

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

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

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

Apex和Database相关知识点有哪些

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

  • Apex是不区分大小写的语言

Apex命名规范(这里我用的是Java的规范)
  1. 类名首字母大写,如果类名由多个单词组成,每个单词的首字母都要大写。 如:

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

int index=0;
public void toString(){}
  1. 常量名全部大写

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<n; i++){
	    result.add('Test'+i); 
	System.debug(result[i]); 
	}
	    return result; 
	}
}
  1. In the Developer Console, click Debug | Open Execute Anonymous Window.

  2. In the window that opens, enter the following.

StringArrayTest.generateStringArray(5);

Apex和Database相关知识点有哪些

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! Apex和Database相关知识点有哪些


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记录,无论是标准记录还是自定义对象记录
Apex和Database相关知识点有哪些

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

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

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

Apex和Database相关知识点有哪些

在处理通用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)
    }
}

Apex和Database相关知识点有哪些

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; 
    }
}

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

Apex和Database相关知识点有哪些


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<n; i++){
            Account acct = new Account(); 
       		acct.Name = 'Acme In'+i; 
            acct.AccountNumber = 'A000'+i; 
          	addAccounts.add(acct); 
        }
        try{
            insert addAccounts; 
        }catch(DMLException e){
            System.debug('A DML Exception has occurred'+e.getMessage()); 
        }
    }
}

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

AccountHandler.insertAccount(10);

效果演示:

  • 执行上述代码前: 我的Acounts下面只有3条记录
    Apex和Database相关知识点有哪些

  • 执行上述代码后: 我的Accounts下面多了10条记录
    Apex和Database相关知识点有哪些 结果Trailhead报错了,我才知道理解错了,我以为Acme Inc n的意思是Acme Inc 1 , Acme Inc 2 , Acme Inc 3.... Apex和Database相关知识点有哪些

改正后的做法:

/*
 * 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<n; 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条数据 Apex和Database相关知识点有哪些

Apex和Database相关知识点有哪些

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];

预备知识

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

  1. 在开发人员控制台

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

/*
 * 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;
        
    }
}

Apex和Database相关知识点有哪些

扩展

与其他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;   
    }
}

Apex和Database相关知识点有哪些

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();

Apex和Database相关知识点有哪些

Map

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

put方法

要将键值对添加到Map,请使用put方法,如下所示:
Apex和Database相关知识点有哪些
put方法需要两个参数:键和值。 让我们创建一个茶类型(键)及其风味特征(值)的映射。

Tea Types and Flavor Profiles

Apex和Database相关知识点有哪些

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);         
    }    
}

Apex和Database相关知识点有哪些

重点

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相关知识点有哪些”有了更深的了解,不妨来实际操作一番吧!这里是创新互联网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

当前文章:Apex和Database相关知识点有哪些
本文网址:https://www.cdcxhl.com/article4/ghccie.html

成都网站建设公司_创新互联,为您提供移动网站建设ChatGPT网站营销关键词优化品牌网站建设用户体验

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联

成都定制网站网页设计