2017-08-08 63 views
0

我正在尋找建立一個動態框架,其中提供了實體對象,我不會有任何當前實體類型的知識。如何獲取JPA實體的子關聯

我在嘗試的是,如果有ManyToOne關聯存在任何子關聯並以不同方式處理它們。

請讓我知道有什麼辦法,我可以找到具有多對一關係子關聯的名字

例如:

//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; 
} 

我將給出類似如下的方法

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

讓我知道有沒有我可以取孩子協會的名字

+1

@ManyToOne註釋在運行時保留。如果他們有這個註釋,你可以檢查字段/方法。 – toongeorges

+0

@toongeorges是否有任何方法可以獲取給定的字段是否註釋了ManyToOne或不。請讓我知道 – Maddy

+1

看到https://stackoverflow.com/questions/4296910/is-it-possible-to-read-the-value-of-a-annotation-in-java#4296964 – PCO

回答

0

夥計們感謝支持那些正在尋找幫助來尋找當前實體的關聯的人這裏是一種方式實體經理有一個元模型對象,您可以檢索當前的實體屬性,如果它是一個關聯或沒有關聯

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; 
}