用法
要訪問儲存在符合 LDAP 規範的目錄中的域實體,您可以使用我們完善的儲存庫支援,這大大簡化了實現。為此,請為您的儲存庫建立一個介面,如下例所示
示例 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
}
這裡我們有一個簡單的領域物件。請注意,它有一個名為 dn 的屬性,型別為 Name。有了這個領域物件,我們可以透過定義一個介面來建立一個儲存庫以持久化該型別的物件,如下所示
示例 2. 用於持久化
Person 實體的基本儲存庫介面public interface PersonRepository extends CrudRepository<Person, Long> {
// additional custom finder methods go here
}
由於我們的領域儲存庫擴充套件了 CrudRepository,它為您提供了 CRUD 操作以及訪問實體的方法。使用儲存庫例項只需將其依賴注入到客戶端中。
示例 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 的單元測試支援建立一個應用程式上下文,該上下文將對測試用例執行基於註解的依賴注入。在測試方法內部,我們使用儲存庫查詢資料儲存。