Search code examples
sqlldapspring-ldapldap-query

How to use "IN" operator from SQL for writing LDAP query


I want to use "IN" operator from SQL for writing LDAP query.

For ex: If I have a list of names called "NameList", I write the following SQL query

SELECT * FROM TABLENAME WHERE NAME IN "NameList"

How do I do write similar LDAP Query?

public static final String[] LDAP_ATTRIBUTE_IDS = {"displayName"};

LdapContext ldapContext = new InitialLdapContext(env, null); \\env has all 
 \\connection details

List NameList = new ArrayList<String>();
NameList.add("ABC");
NameList.add("XYZ");
NameList.add("LMN");

NamingEnumeration namingEnumeration = ldapContext.search("",
"(&(objectCategory=person)(objectclass=user)(|(sAMAccountName=XYZ)(sAMAccountName=LMN)(sAMAccountName=ABC)))", getSearchControls());

Attributes attrs = ((SearchResult) namingEnumeration.next()).getAttributes();
String value = attrs.get(LDAP_ATTRIBUTE_IDS);

Instead on adding XYZ,LMN and ABC using "|" operator I would Like to know if NameList can be used with "IN" operator.


Solution

  • No, there is no equivalent IN operator for searching LDAP.

    Maybe you're not using Active Directory, but AD does support an SQL Dialect for searching, but even then, it doesn't support IN.

    So the only way to do this is the way you already are. If you have your NameList array, you can use String.join to build the query. Something like this:

    NamingEnumeration namingEnumeration = ldapContext.search("",
    "(&(objectCategory=person)(objectclass=user)(|(sAMAccountName=" + String.join(")(sAMAccountName=", NameList) + ")))", getSearchControls());