Definition of ManyToMany vs OneToMany using ClassMetadata

I use ClassMetadata to determine the structure of a sleeping POJO.

I need to determine if the 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 a method to tell me if this is a ManyTo____ relationship. I see getPropertyLaziness (), but this does not always guarantee the type of the collection. Any ideas?

+3
source share
2 answers

This is not easy, unfortunately. It is best to discover this by checking the specific implementation 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
+4
source

This is an opportunity.

: 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");
                }
            }
        }
0

Source: https://habr.com/ru/post/1716819/


All Articles