使用

要访问存储在符合 LDAP 目录中的域实体,您可以使用我们先进的 Repository 支持,它能显著简化实现。 为此,请为您的 Repository 创建一个接口,如下例所示

例 1. Person 实体示例
@Entry(objectClasses = { "person", "top" }, base="ou=someOu")
public class Person {

   @Id
   private Name dn;

   @Attribute(name="cn")
   @DnAttribute(value="cn", index=1)
   private String fullName;

   @Attribute(name="firstName")
   private String firstName;

   // No @Attribute annotation means this is bound to the LDAP attribute
   // with the same value
   private String firstName;

   @DnAttribute(value="ou", index=0)
   @Transient
   private String company;

   @Transient
   private String someUnmappedField;
   // ...more attributes below
}

我们这里有一个简单的域对象。请注意,它有一个类型为 Name 的名为 dn 的属性。有了这个域对象,我们可以创建一个 Repository,通过定义一个接口来持久化该类型的对象,如下所示

例 2. 用于持久化 Person 实体的基本 Repository 接口
public interface PersonRepository extends CrudRepository<Person, Long> {

  // additional custom finder methods go here
}

因为我们的域 Repository 继承了 CrudRepository,所以它为您提供了 CRUD 操作以及访问实体的方法。使用 Repository 实例就是将其依赖注入到客户端中。

例 3. 访问 Person 实体
@ExtendWith(SpringExtension.class)
@ContextConfiguration
class PersonRepositoryTests {

    @Autowired PersonRepository repository;

    @Test
    void readAll() {

      List<Person> persons = repository.findAll();
      assertThat(persons.isEmpty(), is(false));
    }
}

该示例使用 Spring 的单元测试支持创建一个应用程序上下文,该上下文将对测试用例执行基于注解的依赖注入。在测试方法中,我们使用 Repository 查询数据存储。