DML を使用したデータの追加および取得
レコードの挿入または操作を行う前に、レコードデータが sObject としてメモリ内に作成されます。sObject データ型は汎用データ型で、レコードデータを保持する変数のデータ型に対応します。sObject データ型のサブタイプとなる特定のデータ型が存在します。これらは、標準オブジェクトレコード (Account や Contact など) やカスタムオブジェクト (Invoice_Statement__c など) のデータ型に対応します。通常、これらの特定の sObject データ型を使用します。ただし、sObject のデータ型を事前に把握していない場合は、汎用 sObject データ型を使用できます。次に、新しい特定の Account sObject を作成して変数に割り当てる方法の例を示します。
1Account a = new Account(Name='Account Example');前の例では、変数 a で参照される取引先が必須の Name 項目によりメモリ内に存在しています。ただし、これは Lightning プラットフォームの永続レイヤにはまだ保持されていません。DML ステートメントをコールして、sObject をデータベースに保持する必要があります。次に、insert ステートメントを使用してこの取引先を作成および保持する例を示します。
1Account a = new Account(Name='Account Example');
2insert a;また、すでに挿入されているレコードを DML を使用して変更することもできます。実行できる操作は、レコードの更新、レコードの削除、ごみ箱からのレコードの復元、レコードのマージ、リード取引の��始です。レコードを照会すると、変更してその変更を保持できる sObject インスタンスを取得します。次に、以前に保持されている既存のレコードを照会して、メモリ内でこのレコードの sObject の表示に関するいくつかの項目を更新し、その変更をデータベースに保持する例を示します。
1// Query existing account.
2Account a = [SELECT Name,Industry
3 FROM Account
4 WHERE Name='Account Example' LIMIT 1];
5
6// Write the old values the debug log before updating them.
7System.debug('Account Name before update: ' + a.Name); // Name is Account Example
8System.debug('Account Industry before update: ' + a.Industry);// Industry is not set
9
10// Modify the two fields on the sObject.
11a.Name = 'Account of the Day';
12a.Industry = 'Technology';
13
14// Persist the changes.
15update a;
16
17// Get a new copy of the account from the database with the two fields.
18Account a = [SELECT Name,Industry
19 FROM Account
20 WHERE Name='Account of the Day' LIMIT 1];
21
22// Verify that updated field values were persisted.
23System.assertEquals('Account of the Day', a.Name);
24System.assertEquals('Technology', a.Industry);