Search code examples
javaentity-frameworkhibernatejpaeclipselink

How to fetch child association for an JPA entity


I am looking to build a dynamic framework where and entity object is provided and I will not have any knowledge of current entity type.

What I am trying is, if there are any child associations exist with ManyToOne association and process them differently.

Please let me know is there any way i can find child association names which have ManyToOne relationship

example:

    //Parent Class 
public class Person
{
    @OneToMany(cascade = CascadeType.PERSIST, mappedBy = "personName")
    private List<FamilyName> familyNameList = null;
}

    // Child Class 
public class FamilyName
{
    @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.PERSIST)
    @JoinColumn(name = "PERSON_RID", referencedColumnName = "PERSONNAME_RID", nullable = false),
    private PersonNameNonAggregates personName = null;
}

I will be given a method similar as below

private void processEntity(Class<T> persistentClass){
// find child associations of the given persistent class and process 
}

Let me know is there any i can fetch child associations names


Solution

  • Guys thanks for the support for those who are looking for help to find the associations of the current entity here is a way entity Manager has a meta model object and you can retrieve the current entity attributes and if it is a association or not

    public Set<Attribute> fetchAssociates(){
        Set<Attribute> associations = new HashSet();
        Metamodel model = this.entityManager.getMetamodel();
            EntityType cEntity = model.entity(this.persistentClass);
            System.out.println("Current Entity "+cEntity.getName());
            Set<Attribute> attributes =cEntity.getAttributes();
            for(Attribute att : attributes){
                if(att.isAssociation()){
                    associations.add(att);
                }
            }
        return associations;
    }