Spring ldap ODM

Spring ldap ODM
이 글 은 Spring - ldap 기본 동작 을 다 루 고 있 으 며, LdapTemplate 라 는 bean 을 IOC 용기 에 정의 하여 사용 시 LdapTemplate 를 주입 하면 LDAP 디 렉 터 리 트 리 에 대한 CRUD 및 선별, 여과 등 을 완성 할 수 있다.
  • 그러나 선별 조회 한 내용 에 대해 JNDI 는 Attributes 에 봉 인 된 것 입 니 다. spring - ldap 는 Attributes Mapper 인 터 페 이 스 를 제공 하여 Attributes 에서 자바 대상 으로 구체 적 인 논 리 를 실현 하도록 하지만 업무 변화 에 따라 서로 다른 검색 열 에 대해 논 리 를 바 꾸 려 면 다시 써 야 합 니 다.
  • 조 회 된 내용 을 자바 대상 으로 자동 으로 바 꿀 수 있 는 방법 이 있 습 니까? 관계 형 데이터 베이스 ORM 처럼 MySQL 데이터 베이스 에서 조회 한 결과 집합 을 자동 으로 완성 하고 실체 류 와 의 매 핑 을 실행 할 때 대상 목록 을 직접 얻 을 수 있 습 니 다.
  • spring - ldap 역시 해당 하 는 지원 (spring - ldap 2. x 버 전부터), ODM (Object - Directory Mapping) 대상 디 렉 터 리 맵 을 제공 합 니 다.MySQL 데이터베이스 와 달리 LDAP 는 디 렉 터 리 트 리 이 고 트 리 구조의 데이터베이스 입 니 다.

  • spring - ldap 이 프레임 워 크 는 ORM 과 비슷 한 메커니즘 을 제공 하여 LDAP 관련 작업 을 패키지 합 니 다. 주로 1. Session Factory 의 LdapContextSource 를 포함 합 니 다.2. 하 이 버 네 이 트 템 플 릿 등 과 유사 한 LdapTemplate;3. 위조 사무 지원, tx 프레임 워 크 의 TransactionManager 와 혼용 할 수 있 는 지 알 수 없 음;4. JPA 의 사용 @ Entry, @ Attribute, @ Id 에 표 시 된 주해 와 유사 합 니 다.
    ORM 프레임 워 크, 예 를 들 어 Hibernate 나 JPA 는 주 해 를 사용 하여 자바 실체 에 표를 표시 할 수 있 습 니 다.Spring - ldap 는 LDAP 디 렉 터 리 트 리 에 대한 작업 을 수행 하기 위해 비슷 한 기능 을 제공 합 니 다. Ldap Operations 인 터 페 이 스 는 비슷 한 방법 을 많이 제공 합 니 다.
     T findByDn(Name dn, Class clazz)
    
     T findOne(LdapQuery query, Class clazz)
    
     List find(LdapQuery query, Class clazz)
    
     List findAll(Class clazz)
    
     List findAll(Name base, SearchControls searchControls, Class clazz)
    
     List findAll(Name base, Filter filter, SearchControls searchControls, Class clazz)
    
    void create(Object entry)
    void update(Object entry)
    void delete(Object entry)
    

    LdapTemplate 는 이 인 터 페 이 스 를 실 현 했 습 니 다. 이 방법 들 은 모두 LdapTemplate bean 정 의 를 완성 한 후에 주입 하여 사용 할 수 있 습 니 다.우선 기본 공 사 를 완성 한 대로 건설한다.http://www.jianshu.com/p/3aeb49a9befd
    ODM 주해
    맵 을 완성 해 야 하 는 실체 클래스 는 주석 을 사용 해 야 합 니 다.org. spring from work. ldap. odm. annotations package 에서 제공 합 니 다.
  • @ Entry - 실체 클래스 표시 (required)
  • @ Id - 실체 DN 가리 키 기;javax. naming. Name 형식 (required)
  • @ Attribute - 표지 실체 류 가 비 춰 야 할 필드
  • @DnAttribute -
  • @ Transient - 표지 실체 류 에 맵 이 필요 없 는 필드
  • 예시:
    @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;
    
       // No @Attribute annotation means this will be bound to the LDAP attribute
       // with the same value
       private String description;
    
       @DnAttribute(value="ou", index=0)
       @Transient
       private String company;
    
       @Transient
       private String someUnmappedField;
    }
    

    @ Entry 태그, object Classes 정 의 는 object Class 와 완전히 일치 해 야 하 며 여러 값 을 지정 할 수 있 습 니 다.object 를 새로 만 들 고 조회 할 때 ODM 은 이 태그 에 따라 일치 하 며 object Class 를 지정 할 필요 가 없습니다.
    모든 entry 는 @ Id 필드 를 지정 해 야 합 니 다. 형식 은 javax. naming. Name 입 니 다. 사실은 DN 입 니 다.그러나 LdapContextSource 에 base 를 지정 하면 DN 은 base 에 따라 상대 경 로 를 캡 처 합 니 다.예 를 들 어 DN 은 cn = user, ou = users, dc = jayxu, dc = com, base 는 dc = jayxu, dc = com 이 고 추출 한 user 대상 DN 은 cn = user, ou = users 이다.
    LDAP 와 매 핑 할 필요 가 없 는 필드 에 @ Transient 를 사용 하여 표시 합 니 다.
    ODM 조작
        /**
         *       o     
         */
        @Test
        public void findOne(){
            LdapQuery ldapQuery = query().where("o").is("039cb846de0e40e08901e85293f642bf");
            LdapDept dept = ldapTemplate.findOne(ldapQuery, LdapDept.class);
            System.out.println(dept);
        }
    
        /**
         *        
         */
        @Test
        public void filter(){
            LdapQueryBuilder ldapQueryBuilder = query();
            Filter filter = new GreaterThanOrEqualsFilter("modifyTimestamp",timestamp);
            ldapQueryBuilder.filter(filter);
            List depts = ldapTemplate.find(ldapQueryBuilder, LdapDept.class);
            for (LdapDept dept: depts ) {
                System.out.println(dept);
            }
        }
    
        /**
         *       
         *    base, LdapDept  @Entry  
         */
        @Test
        public void getAllDepts(){
            List depts = ldapTemplate.findAll(LdapDept.class);
            for (LdapDept dept: depts ) {
                System.out.println(dept);
            }
        }
    

    그 중에서 LdapDept 는 사용자 정의 실체 클래스 로 Entry, @ Attribute, @ Id 주해 의 약정 에 따라 표시 하면 됩 니 다.
    org. springframework. ldap. pool. factory. Pooling ContextSource 를 사용 하여 연결 탱크 도입
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.PropertySource;
    import org.springframework.ldap.core.ContextSource;
    import org.springframework.ldap.core.LdapTemplate;
    import org.springframework.ldap.core.support.LdapContextSource;
    import org.springframework.ldap.pool.factory.PoolingContextSource;
    import org.springframework.ldap.pool.validation.DefaultDirContextValidator;
    import org.springframework.ldap.transaction.compensating.manager.TransactionAwareContextSourceProxy;
    
    import java.util.HashMap;
    import java.util.Map;
    
    /**
     * LDAP       
     *
     *     LDAP  LdapTemplate    
     */
    @ConfigurationProperties(prefix = "ldap")
    @PropertySource("classpath:/application.yml")
    @Configuration
    public class LdapConfiguration {
    
        private LdapTemplate ldapTemplate;
    
        @Value("${maxActive}")
        private int maxActive;
    
        @Value(value = "${maxTotal}")
        private int maxTotal;
    
        @Value(value = "${maxIdle}")
        private int maxIdle;
    
        @Value(value = "${minIdle}")
        private int minIdle;
    
        @Value(value = "${maxWait}")
        private int maxWait;
    
        @Value(value = "${url}")
        private String LDAP_URL;
    
        @Value(value = "${base}")
        private String BASE_DC;
    
        @Value(value = "${dbusername}")
        private String USER_NAME;
    
        @Value(value = "${password}")
        private String PASS_WORD;
    
        @Bean
        public LdapContextSource contextSource() {
            LdapContextSource contextSource = new LdapContextSource();
            Map config = new HashMap();
    
            contextSource.setUrl(LDAP_URL);
            contextSource.setBase(BASE_DC);
            contextSource.setUserDn(USER_NAME);
            contextSource.setPassword(PASS_WORD);
    
            //             
            config.put("java.naming.ldap.attributes.binary", "objectGUID");
    
            //      ,          
            contextSource.setPooled(true);
            contextSource.setBaseEnvironmentProperties(config);
            return contextSource;
        }
    
        /**
         * LDAP pool   
         * @return
         */
        @Bean
        public ContextSource poolingLdapContextSource() {
            PoolingContextSource poolingContextSource = new PoolingContextSource();
            poolingContextSource.setDirContextValidator(new DefaultDirContextValidator());
            poolingContextSource.setContextSource(contextSource());
            poolingContextSource.setTestOnBorrow(true);//                  
            poolingContextSource.setTestWhileIdle(true);//                    ,          
    
            poolingContextSource.setMaxActive(maxActive <= 0 ? 20:maxActive);
            poolingContextSource.setMaxTotal(maxTotal <= 0 ? 40:maxTotal);
            poolingContextSource.setMaxIdle(maxIdle <= 0 ? 5:maxIdle);
            poolingContextSource.setMinIdle(minIdle <= 0 ? 5:minIdle);
            poolingContextSource.setMaxWait(maxWait <= 0 ? 5:maxWait);
    
            TransactionAwareContextSourceProxy proxy = new TransactionAwareContextSourceProxy(poolingContextSource);
            return proxy;
        }
    
        @Bean
        public LdapTemplate ldapTemplate() {
            if (null == ldapTemplate)
                ldapTemplate = new LdapTemplate(poolingLdapContextSource());
            return ldapTemplate;
        }
    }
    

    ODM 공식 문서https://docs.spring.io/spring-ldap/docs/2.3.2.RELEASE/reference/#odm

    좋은 웹페이지 즐겨찾기