Hello friends, In today's post, I will show you some code example that helps you to query data from salesforce object dynamically. By using this you can query data from any custom or standard sobject.
SOQL builder class for dynamic query
Here I am created three classes that used as helper class to query data. Apex class names are:
1. IllegalStateException
2. SoqlBuilder
3. SoqlBuilderImpl
IllegalStateException.apxc
public class IllegalStateException extends Exception {}SoqlBuilder.apxc
public class SoqlBuilder {SoqlBuilderImpl.apxc
@TestVisible
private SoqlBuilder() {
throw new IllegalStateException('Use SoqlBuilder.newBuilder');
}
public static Selectx newBuilder() {
return new SoqlBuilderImpl();
}
public interface Selectx {
Selectx selectx(String input);
Selectx selectx(Set<String> input);
Fromx fromx(String input);
}
public interface Fromx {
Wherex wherex(String input);
Limitx limitx(Integer input);
Orderx orderx(String input);
String toSoql();
}
public interface Wherex {
Andx andx(String input);
Limitx limitx(Integer input);
Orderx orderx(String input);
String toSoql();
}
public interface Limitx {
Offsetx offsetx(Integer input);
String toSoql();
}
public interface Offsetx {
String toSoql();
}
public interface Andx {
Andx andx(String input);
Limitx limitx(Integer input);
Orderx orderx(String input);
String toSoql();
}
public interface Orderx {
Limitx limitx(Integer input);
String toSoql();
}
}
public class SoqlBuilderImpl implementsExample:
SoqlBuilder.Selectx,
SoqlBuilder.Fromx,
SoqlBuilder.Wherex,
SoqlBuilder.Andx,
SoqlBuilder.Limitx,
SoqlBuilder.Offsetx,
SoqlBuilder.Orderx {
private String soql;
public SoqlBuilderImpl() {
soql = 'SELECT ';
}
public SoqlBuilder.Selectx selectx(String input) {
soql += input;
return this;
}
public SoqlBuilder.Selectx selectx(Set<String> input) {
Boolean firstTime = true;
for (String s : input) {
if (firstTime) {
firstTime = false;
} else {
soql += ',';
}
soql += s;
}
return this;
}
public SoqlBuilder.Fromx fromx(String input) {
soql += ' FROM ' + input;
return this;
}
public SoqlBuilder.Wherex wherex(String input) {
soql += ' WHERE ' + input;
return this;
}
public SoqlBuilder.Andx andx(String input) {
soql += ' AND ' + input;
return this;
}
public SoqlBuilder.Limitx limitx(Integer input) {
soql += ' LIMIT ' + input;
return this;
}
public SoqlBuilder.Offsetx offsetx(Integer input) {
soql += ' OFFSET ' + input;
return this;
}
public SoqlBuilder.Orderx orderx(String input) {
soql += ' ORDER BY ' + input;
return this;
}
public String toSoql() {
return soql;
}
}
List<Account> lstAcc=Database.query(SoqlBuilder.newBuilder()
.selectx('Id,Name,AccountNumber,Type').fromx('Account').wherex('AccountNumber!=null')
.andx('Type != NULL').orderx('Name asc').limitx(10).toSoql());
for(Account ac:lstAcc){
System.debug(ac);
}
Output:
Hope you like this post, for any feedback or suggestions please feel free to comment. I would appreciate your feedback and suggestions.
Thank you.
0 Comments
Post a Comment