Determining ManyToMany vs OneToMany using ClassMetadata

眉间皱痕 提交于 2019-12-06 06:37:58

问题


I am using ClassMetadata to determine the structure of a hibernate POJO.

I need to determine if a collection is OneToMany or ManyToMany. Where is this information? Can I get to it without using reflection? See my code below.


//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.
}

All I need is method to tell me if it's a ManyTo____ relationship. I see getPropertyLaziness(), but that doesn't always guarantee the type of collection. Any ideas?


回答1:


It's not that simple, unfortunatelly. Your best bet to detect this is by checking for particular CollectionPersister implementation:

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



回答2:


This is a possibility.

Direct Known Subclasses: 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");
                }
            }
        }


来源:https://stackoverflow.com/questions/1374748/determining-manytomany-vs-onetomany-using-classmetadata

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!