Search code examples
springspring-bootldapspring-ldapspring-data-ldap

Spring LDAP - multiple bases in one or more request(s)


I need to make a query that will search for all users, located in two different OUs.

For example :

base1: "OU=ou2,OU=ou1"
base2 : "OU=ou3,OU=ou1"

How can I do this with LdapTemplate ? I'm using Spring Boot 3.1.1 and Spring Ldap.

I'd like to be able to do this in a single query, but I understand that this isn't possible. If I run two queries, would it be possible to merge the results without having to manually re-sort?

Many thanks for your answers !


Solution

  • This is the solution I applied (for a searching by Fullname, for example) :

    public List<User> findAllByFullname(String fullname) {      
        LdapQuery query1 = getFullnameQuery(User.BASE1, fullname);
        LdapQuery query2 = getFullnameQuery(User.BASE2, fullname);
    
        List<User> users1 = ldapTemplate.find(query1,User.class);
        List<User> users2 = ldapTemplate.find(query2,User.class);
        
        List<User> users = new ArrayList<>();
        users.addAll(users1);
        users.addAll(users2);
    
        Collections.sort(users, Comparator.comparing(User::getFullname));
        
        return users;
    }
    
    private LdapQuery getUsernameQuery(String base, String username) {
        return LdapQueryBuilder.query().base(base).where("sAMAccountName").is(username);
    }
    

    This is clearly not ideal, so don't hesitate if you have a better solution. Thank you.