问题
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