Force.com중 Apex Code를 정리 합니다.
{|cellspacing="0" cellpadding="2" border="1" width="100%" bgcolor="#FFFFFF" align="center" |- |width="20%" align="center" valign="middle" style="background-color:#eee;"|String |width="80%"|
Boolean : true, false
Date
Datetime
Double
ID : 18 Character Apex record identifier
Integer
String
배열 : [](.md) 로 표시
List zzStr = new List();
zzStr.set(0, "tmpStr");
zzStr.get(0);
zzStr.clear();
Set zzStr = new Set();
zzStr.add("tmpStr");
zzStr.remove(1);
Map zzStr = new Map();
zzStr.put("zzName", "zzValue");
zzStr.get("zzName");
if (~) {
} else {
}
continue, break
do {
statement;
break;
continue;
} while (Boolean_condition);
while (Boolean_condition) {
statement;
}
for (initialization; Boolean_exit_condition; increment) {
statement;
}
for (variable : array_or_set) {
statement;
}
for (variable : [inline_soql_query](inline_soql_query.md)) {
statement;
}
try {
throw ~;
} catch (Exception ex) {
//--- System.ArrayException, DmlException, MathException, NullPointerException
//--- QueryException, StringException, TypeException
} finally {
}
public | private | global
[| abstract | with sharing | without sharing](virtual) class | interface ClassName
[implements InterfaceNameList] [ClassName](extends) {
[public | private | protected | global] [static] [final](final.md) String var = value;
[public | private | protected | global] [override] [static](static.md) String func() { }
}
virtual -> extend or override, abstract -> override
this, super
public virtual class Parent {
public virtual String getStrParent() {
return ‘Parent String’;
}
}
public class Child extends Parent {
public Child() {
super();
}
public override String getStrParent() {
return super.getStrParent() + ‘ : Child String’;
}
}
public Parent() { }
public void Func01() { }
public String getStrParent() {
return strParent;
} }
public class Child extends Parent { public Child() {
super(); //--- Parent의 생성자를 호출 합니다.
//--- TODO : 여기에 코딩
}
//--- Parent의 Method를 재설정 합니다. public override void Func01() {
getStrParent();
} } ```
Interface 상속
public virtual interface Parent {
}
public interface Child extends Parent {
}
상속 확인
[public | private | protected | global] [virtual, abstract, overrid](static,)
String var { [public | private | protected] get; [~](~.md) set;}
public class BasicClass {
public String varName {
get {
return varName;
}
set {
name = value;
}
}
}
public virtual interface Pair {
public T getFirest();
public void setFirst(T val);
}
public StringPair implements Pair {
}
Apex Code로 프로그램을 작성하면 이를 배포하기 위해서는 전체 코딩된 라인중 75% 이상이 테스트 되어야 합니다. (Code Coverage Result가 75% 이상) Force.com에서 제안하는 테스트 방식을 살펴보면 해당 코드가 한번 이상 수행이 되면 테스트가 된 것으로 처리를 하고 있습니다. 따라서 Code Coverage Result를 높이기만을 원한다면 다양한 테스트 코드를 작성할 필요는 없고 각각의 라인이 한번 이상 실행이 되도록 테스트 코드를 작성하면 됩니다.
ClassName 클래스를 테스트하기 위한 Test 클래스 샘플
ClassName의 모든 라인이 수행될 수 있도록 Test 클래스를 작성하여야 함
배포 등을 위해서는 전체 라인중 75%가 테스트(Code Coverage Result)가 되어야 함
@IsTest
private class ClassNameTest {
private static testMethod void testMain() {
ClassName test = null;
//--- Test를 위한 사용자 설정
User user = [id from User where alias='auser'](select);
System.RunAs(u1) {
//--- Test를 위한 데이터 설정
manage = new Manage();
//--- Test 코드 작성
test = new ClassName();
test.setManage(manage);
System.assert(actual==expected, 'Character.isAscii(\'' + charactr + '\') returned ' + actual);
System.assertEquals(singletotalMiles, totalMiles);
Test.startTest(); //--- Limits를 초기화하고 테스트 시작
~
Test.stopTest();
}
}
}
Apex Batch 테스트 프로그램
@IsTest
private class BatEvaluationTest {
private static testmethod void testMain() {
BatEvaluation test = null;
List scope = null;
Test.StartTest();
//--- Apex Batch에 전달할 scope 데이터 생성
scope = new List();
scope.add(new Evaluation__c());
//--- Apex Batch의 각 Method를 별도로 실행
test = new BatEvaluation();
test.start(null);
test.execute(null, scope);
test.finish(null);
Test.stopTest();
}
}
Trigger 종류
Trigger 적용 예외
트리거 메뉴
Trigger 변수
public Integer size = Trigger.size;
public PaymentType__c[](.md) oldData = Trigger.old;
public PaymentType__c[](.md) newData = Trigger.new;
Trigger.old[idx], Trigger.new[idx](idx.md)
Trigger 사례
trigger StandardTrigger on Account (before insert, before update, before delete,
after insert, after update, after delete) {
//--- @future, 비동기 WebService
//--- sObject.addError('~');
//--- Trigger.size, oldMap, newMap, old (ReadOnly), new
if (Trigger.isInsert && Trigger.isBefore) {
for (Account item : Trigger.old) {
}
for (Account item : Trigger.new) {
//--- 수정 가능
}
}
if (Trigger.isInsert && Trigger.isAfter) {
for (Account item : Trigger.old) {
}
for (Account item : Trigger.new) {
}
}
}
- Bulk Triggers
Data import, Bulk Apex API calls, Mass actions
Recursive Apex Code methods and triggers that invoke bulk DML statements
trigger on bulk () {
//--- trigger_event : before insert, before update, before delete, after ~
//--- isInsert, isUpdate, isDelete, isUndelete, isBefore, isAfter
//--- Trigger.new, Trigger.newMap, Trigger.old, Trigger.oldMap, Trigger.size
//--- Trigger.oldMap.get(q.opportunity__c).addError('Cannot delete opportunity with a quote');
//--- Trigger.new[i](i.md).Primary__c.addError('Primary quote cannot be marked non-primary');
try {
Dictionary__c obj = new Dictionary__c(Name='Dictionary deploy test');
insert obj;
} catch(DmlException e) {
System.assert(e.getMessage().contains('first error: FIELD_CUSTOM_VALIDATION_EXCEPTION,'), e.getMessage());
}
} //--- 최대 32,000 characters
trigger helloWorldAccountTrigger on Account (before insert)
{
//--- before insert, before update, after insert, after update, after delete
//--- Trigger.isBefore
Account[](.md) accs = Trigger.new;
MyHelloWorld.addHelloWorld(accs);
Contact c = new Contact(lastName = 'Weissman');
c.accountId = a.Id;
insert c;
List aa = [id, name from account where name = 'Acme'](select);
c = [account.name from contact where id = :c.id](select);
c.account.name = 'salesforce.com';
c.lastName = 'Roth';
update c;
update c.account;
upsert
delete
delete
System.assertEquals('xxx', a.accountNumber);
}
Savepoint sp = Database.setSavepoint();
Database.rollback(sp);
throw ;
try {
} catch () {
}
/**
* 프로그램 명 : DictionaryTrigger.trigger Trigger
* 프로그램 설명 : Dictionary 개체용 Trigger 샘플
* 작성자 : 산사랑
* 작성일 : 2008.06.19 ~ 2008.06.19
*
* Copyright (c) 2000-2008 pnuskgh, All rights reserved.
*/
trigger DictionaryTrigger on Dictionary__c (before insert, before update, before delete)
{
Double tmpNum = 0.0;
if (Trigger.isBefore) {
if (Trigger.isInsert) {
for (Dictionary__c obj:Trigger.new) {
obj.num__c = 1;
}
}
if (Trigger.isUpdate) {
for (Dictionary__c obj:Trigger.new) {
if (obj.num__c == 11) {
obj.num__c = obj.num__c + 100;
} else {
obj.num__c = obj.num__c + 10;
}
if (150 < obj.num__c) {
obj.addError('Error : You can\'t update this record.');
obj.num__c.addError('Error : You can\'t update this record.');
}
}
}
if (Trigger.isDelete) {
for (Dictionary__c obj:Trigger.old) {
tmpNum = obj.num__c;
}
}
}
}
/**
* 프로그램 명 : DictionaryDeployClass Class
* 프로그램 설명 : DictionaryTrigger Trigger를 테스트하는 클래스
* 작성자 : 산사랑
* 작성일 : 2008.06.19 ~ 2008.06.19
*
* Copyright (c) 2000-2008 pnuskgh, All rights reserved.
*/
public class DictionaryDeployClass {
public static testmethod void DictionaryDeployTest()
{
Double tmpNum = 0.0;
System.debug('Start insert trigger test.');
Dictionary__c obj = new Dictionary__c(Name='Dictionary deploy test');
insert obj;
obj = [select Id, Name, num__c
from Dictionary__c
where Id = :obj.Id];
System.assertEquals(1, obj.num__c);
System.debug('Start update trigger test.');
tmpNum = obj.num__c + 10;
update obj;
obj = [select Id, Name, num__c
from Dictionary__c
where Id = :obj.Id];
System.assertEquals(tmpNum, obj.num__c);
try {
System.debug('Start delete trigger test.');
delete obj;
obj = [select Id, Name, num__c
from Dictionary__c
where Id = :obj.Id];
} catch(QueryException e) {
System.debug(e.getMessage());
System.assert(e.getMessage().contains('List has no rows for assignment to SObject'), e.getMessage());
}
}
}
/**
* 프로그램 명 : OpportunityTrigger.trigger Trigger
* 프로그램 설명 : Forecast 데이터만 영업기회에서 분리하여 관리
* 작성자 : 산사랑
* 작성일 : 2008.06.20 ~ 2008.06.20
*
* Copyright (c) 2000-2008 pnuskgh, All rights reserved.
*/
trigger OpportunityTrigger on Opportunity (before insert, after insert, before update, before delete)
{
if (Trigger.isAfter) {
if (Trigger.isInsert) {
for (Opportunity opp:Trigger.new) {
Forecast__c obj = new Forecast__c(OwnerId = opp.OwnerId, Name = opp.Name,
Amount__c = opp.Amount__c, GP__c = opp.GP__c,
Probability__c = opp.Probability, opportunity__c = opp.Id);
insert obj;
}
}
}
if (Trigger.isBefore) {
if (Trigger.isUpdate) {
for (Opportunity opp:Trigger.new) {
Forecast__c obj = [select Id, OwnerId, Name, Amount__c, GP__c, Probability__c, opportunity__c
from Forecast__c
where opportunity__c = :opp.Id];
obj.OwnerId = opp.OwnerId;
obj.Name = opp.Name;
obj.Amount__c = opp.Amount__c;
obj.GP__c = opp.GP__c;
obj.Probability__c = opp.Probability;
update obj;
}
}
if (Trigger.isDelete) {
for (Opportunity opp:Trigger.old) {
Forecast__c obj = [select Id, OwnerId, Name, Amount__c, GP__c, Probability__c, opportunity__c
from Forecast__c
where opportunity__c = :opp.Id];
delete obj;
}
}
}
}
/**
* 프로그램 명 : OpportunityDeployClass Class
* 프로그램 설명 : OpportunityTrigger Trigger를 테스트하는 클래스
* 작성자 : 산사랑
* 작성일 : 2008.06.20 ~ 2008.06.20
*
* Copyright (c) 2000-2008 pnuskgh, All rights reserved.
*/
public class OpportunityDeployClass {
public static testmethod void OpportunityDeployTest()
{
Boolean flagError = false;
Forecast__c obj = Null;
System.debug('Start insert trigger test.');
Opportunity opp = new Opportunity(Name = 'Deploy test', Amount__c = 100, GP__c = 20,
StageName = '수주확신(90%)', CloseDate = System.today());
insert opp;
opp = [select Id, OwnerId, Name, Amount__c, GP__c, Probability
from Opportunity
where Id = :opp.Id];
obj = [select Id, OwnerId, Name, Amount__c, GP__c, Probability__c, opportunity__c
from Forecast__c
where opportunity__c = :opp.Id];
System.assertEquals(opp.OwnerId, obj.OwnerId);
System.assertEquals(opp.Name, obj.Name);
System.assertEquals(opp.Amount__c, obj.Amount__c);
System.assertEquals(opp.GP__c, obj.GP__c);
System.assertEquals(opp.Probability, obj.Probability__c);
System.assertEquals(opp.Id, obj.opportunity__c);
System.debug('Start update trigger test.');
opp.GP__c = 30;
update opp;
obj = [select Id, OwnerId, Name, Amount__c, GP__c, Probability__c, opportunity__c
from Forecast__c
where opportunity__c = :opp.Id];
System.assertEquals(opp.OwnerId, obj.OwnerId);
System.assertEquals(opp.Name, obj.Name);
System.assertEquals(opp.Amount__c, obj.Amount__c);
System.assertEquals(opp.GP__c, obj.GP__c);
System.assertEquals(30, obj.GP__c);
System.assertEquals(opp.Probability, obj.Probability__c);
System.assertEquals(opp.Id, obj.opportunity__c);
try {
System.debug('Start delete trigger test.');
delete opp;
obj = [select Id, OwnerId, Name, Amount__c, GP__c, Probability__c, opportunity__c
from Forecast__c
where opportunity__c = :opp.Id];
} catch(QueryException e) {
if (e.getMessage().contains('List has no rows for assignment to SObject')) {
flagError = true;
} else {
throw e;
}
}
System.assert(flagError);
}
}
"설정 -> App 설정 -> 개발 -> Apex 클래스 -> Apex 예약" 메뉴
"설정 -> 관리 설정 -> 모니터링 -> 예약된 작업" 메뉴에서 모니터링
Scheduler 생성
global class StandardScheduler implements Schedulable {
global void execute (SchedulableContext sc) {
Batchable batch = null;
//--- sc.getTriggerId() CronTrigger 개체
batch = new Batchable();
Database.executebatch(batch);
}
}
Scheduler 사용법
String sch = ‘20 30 8 10 2 ? * ‘;
String id = system.schedule(‘name’, sch, StadnardScheduler);
Apex Code에서 Batch 프로그램을 작성하려면 Database.Batchable Interface를 구현 하여야 합니다.
Apex Batch에서 HTTP request를 호출하는 프로그램을 작성하려면 Database.AllowsCallouts Interface를 implement 하여야 합니다.
Apex Batch 처리를 위한 Class에서 선언한 변수의 값을 계속 유지하려면 Database.Stateful Interface를 implement 하여야 합니다.
ID batchId = null;
BatSession batch = null;
batch = new BatSession();
batchId = Database.executeBatch(batch);
//batchId = Database.executeBatch(batch, 200); //--- 200. 한번에 처리하는 레코드 갯수
Batch Apex 선언
global class BatAccount implements Database.Batchable, Database.Stateful {
global Database.QueryLocator start(Database.BatchableContext ctx) {
return Database.getQueryLocator([Id, Name FROM Account](SELECT));
}
global void execute(Database.BatchableContext ctx, List scope) {
for (Account item : scope) {
}
}
global void finish(Database.BatchableContext ctx) {
ID id = ctx.getJobID(); //--- AsyncApexJob 개체
}
}
Batch Apex 사례
global class BatSession implements Database.Batchable, Database.Stateful {
global Database.QueryLocator start(Database.BatchableContext ctx) {
Datetime tmpDate = null;
tmpDate = Datetime.now();
tmpDate.addDays(-3);
return Database.getQueryLocator([SELECT Id
FROM Session__c
WHERE CreatedDate < :tmpDate]);
}
global void execute(Database.BatchableContext ctx, List scope) {
delete scope;
}
global void finish(Database.BatchableContext ctx) {
AsyncApexJob job = null;
AsyncApexJob job = [SELECT Id, Status, NumberOfErrors, JobItemsProcessed, TotalJobItems, CreatedBy.Email
FROM AsyncApexJob
WHERE Id = :ctx.getJobId()];
}
}
Web Services 생성 in Apex Code
global class StandardWebServices {
webService static String getTitle(String title, Account argAccount) {
return '[+ title + '](')';
}
}
Web Services 호출 in Visualforce Page
var account = sforce.sObject("Account"); //--- id, type, name
var title = sforce.apex.execute(“StandardWebServices”, “getTitle”,
{title:”~”, argAccount:account});
Http http = null;
HttpRequest req = null;
HttpResponse res = null;
String strHeader = null;
String contentType = null, response = null;
try {
req = new HttpRequest();
req.setEndpoint('http://www.apexdevnet.com/');
req.setMethod('GET');
req.setHeader(‘Content-Type’, ‘application/soap+xml’);
req.setTimeout(60000);
req.setBody(‘name1=value1&name2=value2’);
req.setCompressed(false);
//--- Basic Authencation
strHeader = EncodingUtil.base64Endoce(Blob.valueOf(userid + ‘:’ + pwd))
req.setHeader(‘Authorization’, ‘BASIC ‘ + strHeader);
http = new Http();
res = http.send(req);
if (res.getStatusCode() == 404) {
} else {
contentType = resp.getHeader('Content-Type');
response = resp.getHeader('Content-Length');
this.theXMLDom = new xmldom(res.getBody());
dom.document doc = res.getBodyDocument();
dom.XmlNode [](.md) node = doc.getRootElement().getChildElements();
//--- Atachement로 저장
Attachment attach = new Attachment();
attach.Name = “~’;
attach.ContentType = “~”;
attach.body = Blob.valueOf(res.getBody());
attach.ParenetId = ~;
insert attach;
}
} catch (System.CalloutException e) {
this.theXMLDom = null;
}
RemoteAction은 Visualforce Page에서 JavaScript를 사용하여 Controller의 Method를 호출하는 방법 입니다.
Apex Code
global class MyJSController {
public String accountName { get; set; }
public static Account account { get; set; }
@RemoteAction
global static Account getAccount(String accountName) {
account = [
SELECT id, name, phone
FROM Account
WHERE name = :accountName ];
return account;
}
}
Visualforce Page
var accountNameJS = null;
accountNameJS = "오픈소스 비즈니스 컨설팅";
MyJSController.getAccount(
accountNameJS, //--- 전달되는 인자
function(result, event) { //--- result : 반환 값
if (event.status) {
//--- 정상 처리
//--- 반환된 값은 result.name
//--- 반환된 배열 result[2](2.md).name
} else if (event.type === 'exception') {
//--- Exception 오류 처리
} else {
//--- 오류 처리
}
},
{escape:true}
);
참고 문헌
Single Mail 발송
Messaging.SingleEmailMessage email = null;
Messaging.EmailFileAttachment file = null;
Messaging.SendEmailResult[](.md) result = null;
email = new Messaging.SingleEmailMessage();
email.setSubject(String);
email.setToAddress(String[](.md));
email.setPlainTextBody(String);
file = new Messaging.EmailFileAttatchment();
file.setFileName(‘~’);
file.setBody(Blob);
email.setFileAttachments(new Messaging.EmailFileAttachment[](.md) {file});
result = Messaging.sendEmail(new Messaging.SingleEmailMessag[](.md) {email});
{|cellspacing="0" cellpadding="2" border="1" width="100%" bgcolor="#FFFFFF" align="center" |- |width="25%" align="center" valign="middle" style="background-color:#eee;"|sObject |width="75%" valign="top"|
동적으로 데이터 읽기
sObject item = Database.query(string_limit_1);
List data = Database.query(string);
동적으로 데이터 처리하는 샘플
List data = null;
Map columns = null;
data = Database.query(strQuery);
columns = data.getSObjectType().getDescribe().fields.getMap();
for (sObject item : data) {
for (String name : columns.keySet()) {
string value = null;
value = String.valueOf(item.get(name));
}
}
참고 문헌
공유 권한 : 소유자 -> 역할 -> 공유 설정 / 필드 접근성
User Managed Sharing
Access Level : None. Private, Read. Read Only, Edit. Read/Write, All. Full Access
개체명__Share
Modify All Data" 권한이 있어야 사용 가능
public class JobSharing {
public Boolean manualShare(ID recordId, ID userOrGroup) {
Job__Share share = new Job__Share();
share.ParentId = recordId;
share.UserOrGroup = userOrGroup; //--- Job.Recruiter__c
share.AccessLevel = ‘Read’;
share.RowCause = Schema.Job__Share.RowCause.Manual;
//--- 공유 이유가 Recruite일 경우 (사용자 정의 공유 이유)
//--- share.RowCause = Schema.Job__Share.RowCause.Recruite__c;
Database.insert(share);
}
}
apex-library의 JSONObject를 사용하여 JSON 데이터를 처리할 수 있습니다.
JSONObject Class
Boolean has(String key)
SET keys()
JSONObject putOpt(String key, JSONObject.value value)
JSONObject.value getValue(String key)
Object get(String key)
Object opt(String key) //--- Default는 null을 반환
String getString(String key) //--- Integer.valueOf(string), Date.valueOf(string) 등을 사용하여 다른 type으로 변환 가능
Boolean getBoolean(String key) Boolean optBoolean(String key) //--- Default는 false Boolean optBoolean(String key, Boolean defaultValue) String valueToString()
- 데이터 읽어 오는 함수의 응용
JSONObject snbJson = new JSONObject(strJson); for (JSONObject.value jsonItem : snbJson.getValue('data').values) { JSONObject item = null;
item = new JSONObject(jsonItem.valueToString()); } ```
JSONObject.value Class의 속성값
JSONObject obj
String str
Integer num
Double dnum
Boolean bool
List values
참고 문헌
ApexPages.currentPage().getParameters().get('id');
{!$CurrentPage.parameters.cid}
Cookie는 일반적으로 도메인을 기준으로 설정이 됩니다. 세일즈포스닷컴은 CRM 서비스를 제공하는 URL과 Visualforce의 URL이 다르므로 서로 다른 도메인의 URL을 가지게 됩니다.
세일즈포스닷컴의 URL 종류
Apex Code에서 Cookie 사용 방법
public class UtilCookie {
public static String getCookie(String name) {
Cookie cookie = null;
cookie = ApexPages.currentPage().getCookies().get(name);
if (cookie == null) {
return null;
} else {
return cookie.getValue();
}
}
//--- 저장되는 Cookie명은 "apex__" + name 입니다.
public static void setCookie(String name, String value) {
Cookie cookie = null;
cookie = new Cookie(name, value, null, -1, false);
ApexPages.currentPage().setCookies(new Cookie[](.md){ cookie });
}
}
JavaScript에서 Cookie 사용 방법
사용자 세션을 활용하여 세션 정보를 관리하는 모듈을 작성 합니다.
Session의 종류
UserInfo.getSessionID();
{!$Api.Session_ID}
var __sfdcSessionId = "{!GETSESSIONID()}";
//--- sforce.connection.sessionId 에 저장되어 사용됨
Session__c 개체
DaoSession
public class DaoSession {
public String sessionId {get; set;}
public DaoSession(String argSessionId) {
sessionId = argSessionId;
}
public String findData(String argName) {
Session__c session = null;
session = [SELECT Id, Name, SessionId__c, Name__c, Value__c, LastModifiedDate
FROM Session__c
WHERE SessionId__c = :sessionId
AND Name__c = :argName
LIMIT 1];
return session.Value__c;
}
public void insertData(String argName, String argValue) {
Session__c session = null;
session = new Session__c();
session.SessionId__c = sessionId;
session.Name__c= argName;
session.Value__c = argValue;
insert session;
}
public void updateData(String argName, String argValue) {
Session__c session = null;
session = [SELECT Id, Name, SessionId__c, Name__c, Value__c, LastModifiedDate
FROM Session__c
WHERE SessionId__c = :sessionId
AND Name__c = :argName
LIMIT 1];
session.Value__c = argValue;
update session;
}
public Void upsertData(String argName, String argValue) {
Session__c session = null;
try {
session = [SELECT Id, Name, SessionId__c, Name__c, Value__c, LastModifiedDate
FROM Session__c
WHERE SessionId__c = :sessionId
AND Name__c = :argName
LIMIT 1];
} catch (Exception ex) {
}
if (session == null) {
session = new Session__c();
session.SessionId__c = sessionId;
session.Name__c= argName;
session.Value__c = argValue;
insert session;
} else {
session.Value__c = argValue;
update session;
}
}
public Void deleteData(String argName) {
Session__c session = null;
session = [SELECT Id, Name, SessionId__c, Name__c, Value__c, LastModifiedDate
FROM Session__c
WHERE SessionId__c = :sessionId
AND Name__c = :argName
LIMIT 1];
delete session;
}
}
MgrSession
public class MgrSession {
public DaoSession dao = null;
public MgrSession() {
dao = new DaoSession(UserInfo.getSessionId());
}
public String getSession(String argName) {
return dao.findData(argName);
}
public Void setSession(String argName, String argValue) {
dao.upsertData(argName, argValue);
}
}
SchSession
global class SchSession implements Schedulable {
global void execute(SchedulableContext sc) {
BatSession batch = null;
batch = new BatSession();
Database.executeBatch(batch);
}
}
BatSession
global class BatSession implements Database.Batchable {
global Database.QueryLocator start(Database.BatchableContext ctx) {
Datetime tmpDate = null;
tmpDate = Datetime.now();
tmpDate.addDays(-3);
return Database.getQueryLocator([SELECT Id
FROM Session__c
WHERE CreatedDate < :tmpDate]);
}
global void execute(Database.BatchableContext ctx, List scope) {
delete scope;
}
global void finish(Database.BatchableContext ctx) {
}
}
ConfigSetting__c Custom Settings
MgrConfig
public class MgrConfig {
public MgrConfig() {
}
public String getConfig(String argName) {
ConfigSetting__c config = null;
config = ConfigSetting__c.getValues(argName);
return config.Value__c;
}
}
Config__c 개체
DaoConfig
public class DaoConfig {
public static String CATEGORY = 'global';
public DaoConfig() {
}
public String findData(String argCategory, String argName) {
Config__c config = null;
config = [SELECT Id, Name, Category__c, Name__c, Value__c
FROM Config__c
WHERE Category__c = :argCategory
AND Name__c = :argName
LIMIT 1];
return config.Value__c;
}
public String findData(String argName) {
return findData(CATEGORY, argName);
}
public void insertData(String argCategory, String argName, String argValue) {
Config__c config = null;
config = new Config__c();
config.Category__c = argCategory;
config.Name__c = argName;
config.Value__c = argValue;
insert config;
}
public void insertData(String argName, String argValue) {
insertData(CATEGORY, argName, argValue);
}
public void updateData(String argCategory, String argName, String argValue) {
Config__c config = null;
config = [SELECT Id, Name, Category__c, Name__c, Value__c
FROM Config__c
WHERE Category__c = :argCategory
AND Name__c = :argName
LIMIT 1];
config.Value__c = argValue;
update config;
}
public void updateData(String argName, String argValue) {
updateData(CATEGORY, argName, argValue);
}
public Void upsertData(String argCategory, String argName, String argValue) {
Config__c config = null;
try {
config = [SELECT Id, Name, Category__c, Name__c, Value__c
FROM Config__c
WHERE Category__c = :argCategory
AND Name__c = :argName
LIMIT 1];
} catch (Exception ex) {
}
if (config == null) {
config = new Config__c();
config.Category__c= argCategory;
config.Name__c= argName;
config.Value__c = argValue;
insert config;
} else {
config.Value__c = argValue;
update config;
}
}
public Void upsertData(String argName, String argValue) {
upsertData(CATEGORY, argName, argValue);
}
public Void deleteData(String argCategory, String argName) {
Config__c config = null;
config = [SELECT Id, Name, Category__c, Name__c, Value__c
FROM Config__c
WHERE Category__c = :argCategory
AND Name__c = :argName
LIMIT 1];
delete config;
}
public Void deleteData(String argName) {
deleteData(CATEGORY, argName);
}
}
MgrConfig
public class MgrConfig {
public DaoConfig dao = null;
public MgrConfig() {
dao = new DaoConfig();
}
public String getConfig(String argCategory, String argName) {
return dao.findData(argCategory, argName);
}
public String getConfig(String argName) {
return dao.findData(argName);
}
public Void setConfig(String argCategory, String argName, String argValue) {
dao.upsertData(argCategory, argName, argValue);
}
public Void setConfig(String argName, String argValue) {
dao.upsertData(argName, argValue);
}
}