salesforce 零基础学习(五十六)实现getById
本来想通过template封装DAO中的getById,结果template中无法选择$(object_name),所以此种想法打消了,直接封装成一个Helper类,方便以后项目中如果有类似需要可以使用。
1 public virtual with sharing class ObjectDAOHelper { 2 /* 3 * @param sObjectName sobject api name 4 * @param id sobject record id 5 * return 返回此记录ID,如果不存在返回null 6 */ 7 public static sObject getById(String sObjectName,String id) { 8 String queryStr = 'select '; 9 List<Schema.DescribeSObjectResult> sObjectResults = Schema.describeSObjects(new List<String>{sObjectName}); 10 if(sObjectResults == null || sObjectResults.size() == 0) { 11 return null; 12 } 13 Schema.DescribeSObjectResult sObjectResult = sObjectResults.get(0); 14 Map<String,SObjectField> maps = sObjectResult.fields.getMap(); 15 Integer i = 0; 16 for(Schema.SObjectField objectField : maps.values()) { 17 Schema.DescribeFieldResult fieldResult = objectField.getDescribe(); 18 if(fieldResult.isAccessible()) { 19 queryStr += fieldResult.getName(); 20 if(i != maps.keySet().size() - 1) { 21 queryStr += ','; 22 } 23 i++; 24 } 25 } 26 queryStr += ' from ' + sObjectName + ' where Id = :id'; 27 system.debug('queryStr : ' + queryStr); 28 List<sObject> objects = Database.query(queryStr); 29 if(objects == null || objects.size() == 0) { 30 return null; 31 } 32 return objects.get(0); 33 } 34 }
运行代码:
结果展示:
queryStr : select Id,OwnerId,IsDeleted,Name,RecordTypeId,CreatedDate,CreatedById,LastModifiedDate,LastModifiedById,SystemModstamp,LastViewedDate,LastReferencedDate,GoodsName__c,GoodsBrand__c,GoodsPrice__c,GoodsCostPrice__c,GoodsPicture__c,Status__c,Goods_Code_Unique__c,GoodsDescribe__c,GoodsProfit__c,No__c from Goods__c where Id = :id
{
"attributes" : {
"type" : "Goods__c",
"url" : "/services/data/v38.0/sobjects/Goods__c/a052800000Ejg1vAAB"
},
"Id" : "a052800000Ejg1vAAB",
"OwnerId" : "00528000002JyclAAC",
"IsDeleted" : false,
"Name" : "a052800000Ejg1v",
"RecordTypeId" : "01228000000U1u0AAC",
"CreatedDate" : "2016-12-13T07:16:03.000+0000",
"CreatedById" : "00528000002JyclAAC",
"LastModifiedDate" : "2016-12-13T07:16:03.000+0000",
"LastModifiedById" : "00528000002JyclAAC",
"SystemModstamp" : "2016-12-13T07:16:03.000+0000",
"GoodsName__c" : "测试商品1",
"GoodsBrand__c" : "其他",
"GoodsPrice__c" : 200.000000,
"GoodsCostPrice__c" : 100.000000,
"Goods_Code_Unique__c" : "GC00001",
"GoodsDescribe__c" : "测试描述",
"GoodsProfit__c" : 100.00,
"No__c" : "2016-142"
}
总结:简单的helper类以及方法,篇中有问题的欢迎指出,不懂得欢迎留言。
作者:zero
博客地址:http://www.cnblogs.com/zero-zyq/
本文欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接
如果文章的内容对你有帮助,欢迎点赞~
为方便手机端查看博客,现正在将博客迁移至微信公众号:Salesforce零基础学习,欢迎各位关注。