Find all classes that reference a given class either through a one-to-one relationship or a one-to-one relationship

I can find the tables in the database referenced by this table through a link to a foreign key. In particular, in mysql , this is done through:

SELECT * FROM REFERENTIAL_CONSTRAINTS WHERE REFERENCED_TABLE_NAME = 'table_name'; 

I want to achieve this functionality with java code.

That is, I want to find all classes that reference this class either through a one-to-one or one-to-one relationship .

+4
source share
3 answers

This can be done in NHibernate (not Hibernate) as follows.

 IList<string> classList = new List<string(); ICollection<PersistentClass> persistentClasses = Configuration.ClassMappings; foreach (var persistentClass in persistentClasses) { foreach (var property in persistentClass.PropertyIterator) { if(property.Type.IsAssociationType == true && property.Type.ReturnedClass.Name == "GivenClassName") { classList.Add(persistentClass.EntityName); } } } return classList; 

All class mappings are deleted in the collection and repeated to find the relationship between their properties and the specified class. I think Hibernate also has similar APIs, so this can be done in Hibernate too. Also note that this code is in C #, but I thought that maybe looking at it you could write similar code in Java too.

See this answer for a demonstration of similar APIs in Hibernate.

+2
source

If you are using an IDE such as Eclipse or netbeans, this can help you find a hierarchy of setter or getter calls of the type corresponding to the class "table_name"

0
source

I just stumbled upon this problem; so here is a very late answer with a Hibernate version of a possible solution:

 import org.hibernate.metadata.ClassMetadata; import org.hibernate.type.EntityType; import org.hibernate.type.Type; [...] Set<Class<?>> referencingClasses = new HashSet<Class<?>>(); for (Entry<String, ClassMetadata> entry:sessionFactory.getAllClassMetadata().entrySet()) { Class<?> clazz=entry.getValue().getMappedClass(); for (String propertyName: entry.getValue().getPropertyNames()) { Type t=entry.getValue().getPropertyType(propertyName); if (t instanceof EntityType) { EntityType entityType=(EntityType)t; if (entityType.getAssociatedEntityName().equals(YourClass.class.getName())) referencingClasses.add(clazz); } } } 
0
source

All Articles