Reputation: 126
I can find tables in a database referenced by a given table through foreign key reference. Specifically in mysql, it is done through:
SELECT * FROM REFERENTIAL_CONSTRAINTS WHERE REFERENCED_TABLE_NAME = 'table_name';
I want to achieve this functionality through java code.
That is, I want to find all classes that reference a given class either through many-to-one or one-to-one relationship.
Upvotes: 4
Views: 220
Reputation: 342
I just stumbled upon this problem myself; so here's 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);
}
}
}
Upvotes: 0
Reputation: 3281
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 the class mappings are retreived in a collection and are iterated to find associations between their properties and a given class. I think Hibernate too has similar APIs so this can be done in Hibernate too. Also note that this code is in C#, but I thought maybe looking at it you can write similar code in Java too.
See this answer which demonstrates similar APIs in Hibernate.
Upvotes: 2
Reputation: 1669
If you are using an IDE like Eclipse or netbeans, this may help you alot through searching for call hierarchy of setters or getters of the type the class corresponding to 'table_name'
Upvotes: 0