2009-09-03 2 views
3

ClassMetadata를 사용하여 최대 절전 모드 POJO의 구조를 결정합니다.ClassMetadata를 사용하는 ManyToMany 대 OneToMany 결정

컬렉션이 OneToMany인지 ManyToMany인지 확인해야합니다. 이 정보는 어디에 있습니까? 리플렉션을 사용하지 않고도 사용할 수 있습니까? 아래 내 코드를 참조하십시오.


//Get the class' metadata 
ClassMetadata cmd=sf.getClassMetadata(o.getClass()); 

for(String propertyName:cmd.getPropertyNames()){ 
    if (cmd.getPropertyType(propertyName).isCollectionType() && cmd.??()) //Do something with @ManyToMany collections. 
} 

내가 필요한 것은 ManyTo____ 관계인지 여부를 알려주는 방법입니다. getPropertyLaziness()를 볼 수는 있지만 컬렉션의 유형을 항상 보장하지는 않습니다. 어떤 아이디어?

답변

4

불행히도 간단하지 않습니다. 이를 감지하는 가장 좋은 방법은 특정 CollectionPersister 구현을 위해 확인하는 것입니다 :

SessionFactory sf = ...; 

// Get the class' metadata 
ClassMetadata cmd = sf.getClassMetadata(o.getClass()); 

for(String propertyName:cmd.getPropertyNames()) { 
    Type propertyType = cmd.getPropertyType(propertyName); 
    if (propertyType.isCollectionType()) { 
    CollectionType collType = (CollectionType) propertyType; 

    // obtain collection persister 
    CollectionPersister persister = ((SessionFactoryImplementor) sf) 
     .getCollectionPersister(collType.getRole()); 

    if (persister instanceof OneToManyPersister) { 
     // this is one-to-many 
    } else { 
    // this is many-to-many OR collection of elements 
    } 
    } // if 
} // for 
+0

완료 !!! 보너스 질문 : @OneToOne을 통해 @ManyToOne을 결정하는 방법은 무엇입니까? – User1

+0

오 기다려 라. 나는 그것을 발견했다고 생각한다. EntityType.isOneToOne(). 그러나, 나는 너없이 이것을 발견 할 수 없었다. 모든 도움에 정말 감사드립니다! 귀하의 출품작은 저와 다른 사람들에게 도움이됩니다. 잘 했어! – User1

+0

너무 빨리 말한 것 같습니다. EntityType.isOneToOne()은 어떤 이유로 든 항상 거짓입니다. OneToOnePersister를 찾지 못했습니다. 어떤 아이디어? – User1

0

이것은 가능성이다.

직접 알려진 서브 클래스 : ManyToOneType, OneToOneType.

 SessionFactory sf = ...; 

     ClassMetadata cmd = sf.getClassMetadata(o.getClass()); 

     for (String propertyName : cmd.getPropertyNames()) { 
      Type propertyType = cmd.getPropertyType(propertyName); 

      if (propertyType.isEntityType()) { 
       EntityType entityType = (EntityType) propertyType; 

       if (entityType instanceof ManyToOneType) { 
        System.out.println("this is ManyToOne"); 
       } else if (entityType instanceof OneToOneType) { 
        System.out.println("this is OneToOne"); 
       } 
      } 
     }