根据项目需求,我们需要动态配置数据,所以在SOQL语句中,我们要获得所有的字段,然后找到了下面的解决方案,具体参考下面的代码:
public String getFieldsSOQL(String objectName){
String selects = '';
// Get a map of field name and field token
Map<String, Schema.SObjectField> fMap = Schema.getGlobalDescribe().get(objectName.toLowerCase()).getDescribe().Fields.getMap();
list<string> selectFields = new list<string>();
if (fMap != null) {
for (Schema.SObjectField ft : fMap.values()) { // loop through all field tokens (ft)
Schema.DescribeFieldResult fd = ft.getDescribe(); // describe each field (fd)
selectFields.add(fd.getName());
}
}
if (!selectFields.isEmpty()) {
for (string s:selectFields) {
selects += s + ',';
}
if (selects.endsWith(',')) {
selects = selects.substring(0,selects.lastIndexOf(','));
}
}
if (selects == null || selects == '') {
selects = 'id';
}
return selects;
}
通过下面的代码可以得到字段拼接的字符串,在Apex中使用的时候需要拼接SOQL语句,参考如下的用法:
String selects = getFieldsSOQL();
String query = 'SELECT '+selects +' FROM Lead';
List<Lead> leadList = Database.getQueryLocator(query);