2015-06-21 38 views
0
@Entity 
@Table(name="MY_TABLE") 
public class MyTable{ 

    @Id 
    @Column(name="MY_TABLE_ID") 
    @GeneratedValue(strategy = GenerationType.AUTO ,generator="SQ_MY_TABLE")  
    @SequenceGenerator(name="SQ_MY_TABLE", sequenceName="SQ_MY_TABLE") 
    private Long myTableId; 

我如何,使用反射,從我的POJO的主鍵列名,與javax.persistence.Id註釋中定義的?我必須找到@Id,然後得到@Column註釋的name屬性...我不知道該怎麼做...獲取ID列名,使用反射

謝謝!

回答

1

這是全由自己動手解決方案:

public static String getPKColumnName(Class<?> pojo) { 

    if (pojo == null) 
     return null; 

    String name = null; 

    for (Field f : pojo.getDeclaredFields()) { 

     Id id = null; 
     Column column = null; 

     Annotation[] as = f.getAnnotations(); 
     for (Annotation a : as) { 
      if (a.annotationType() == Id.class) 
       id = (Id) a; 
      else if (a.annotationType() == Column.class) 
       column = (Column) a; 
     } 

     if (id != null && column != null){ 
      name = column.name(); 
      break; 
     } 
    } 

    if (name == null && pojo.getSuperclass() != Object.class) 
     name = getPKColumnName(pojo.getSuperclass()); 

    return name; 
} 

只是擡頭:這不會對複合主鍵的工作。

+0

當ID的聲明在'MappedSuperclass'中時,這將不起作用。但是你可以在最後添加一個'if(name == null)return getPkColumnName(pojo.getSuperclass());'。 –

+0

@TobiasLiefke感謝您的信息。我更改了代碼。 – Brian