2010-09-07 56 views
2

我想更新我在Java中的知識,因爲我上次在1.4.X版本中使用它時...我試圖使用1.6.0,特別是Java持久性API(2.0)。JPA/EclipseLink - 檢索列名

我設法創建了一個實體類。它工作,因爲我能夠存儲和檢索數據。

但我打打鬧鬧,當我決定來填充表的列名的JList並沒有得到成功......

這是一個簡單的類,看起來像:

@Entity 
@Table(name = "T_CURRENCY", schema = "APP") 
public class Currency implements Serializable { 
    @Transient 
    private PropertyChangeSupport changeSupport = new PropertyChangeSupport(this); 
    private static final long serialVersionUID = 1L; 
    @Id 
    @GeneratedValue(strategy = GenerationType.IDENTITY) 
    @Column(name = "ID") 
    private Short id; 
    @Basic(optional = false) 
    @Column(name = "NAME") 
    private String name; 

    ... 
} 

有沒有辦法檢索列名?我發現這個post。似乎是一個有效的解決方案,但我認爲它可能更容易/優雅的東西?我不知道爲什麼,但我期待已完成的方法...

TIA,

鮑勃

回答

9

可以解析列註釋:

for (Field field : entity.getClass().getDeclaredFields()) { 
    Column column = field.getAnnotation(Column.class); 
    if (column != null) { 
     columnNames.add(column.name()); 
    } 
} 

注意, Column註釋是可選的,所以你必須確保你有它的定義。如果沒有,你將不得不諮詢名字翻譯機制,這對於這個太過分了。

+2

列註釋是可選的 – unbeli 2010-09-07 18:30:23

+0

我知道它是。但在他的情況下,它不是。我會添加一個關於它的註釋。 – Bozho 2010-09-07 18:32:29

+0

'Class#isAnnotationPresent'方法是檢查註釋是否存在的更好方法。 – Lii 2014-08-29 09:47:59

1

但我打打鬧鬧,當我決定來填充表的列名的JList並沒有得到成功......

好,同時可以解析註解(正如Bozho所指出的那樣),JPA的全部意義在於從業務對象中抽象出表和列的名稱(甚至可以使用默認值,使得信息甚至不存在)。換句話說,我不會依賴它們,而是使用類名稱和屬性名稱。

+0

獲得一個字段我真的希望在JPA 2.0中的元數據API將有東西提供,但據我瞭解,它不包括列信息。 – Bozho 2010-09-07 12:07:59

+0

正確,元數據API不包含列信息。 – James 2010-09-07 14:06:00

9

在EclipseLink中,您可以獲取類的ClassDescriptor並獲取其字段(DatabaseField)。

em.unwrap(Session.class).getDescriptor(Currency.class).getFields() 

您還可以得到映射,表格,或其他任何你的願望。

見, http://www.eclipse.org/eclipselink/api/2.1/org/eclipse/persistence/descriptors/ClassDescriptor.html

+0

謝謝。它工作,但getFields()返回一個棄用的向量。所以我會使用Bozho的建議。 – 2010-09-07 20:07:01

+0

向量不被棄用...但使用列出其接口,(List)getFields() – James 2010-09-08 13:05:02

2

屬性和列從的EclipseLink ClassDescriptor

// Get the session object 

org.eclipse.persistence.sessions.Session session = 
    ((org.eclipse.persistence.internal.jpa.EntityManagerImpl) 
       em.getDelegate()).getSession(); 

// Get your desire class descriptor and mapping list 

List<org.eclipse.persistence.mappings.DatabaseMapping> datamap = 
    (List) session.getDescriptor(YOUR_ENTITY_CLASS_NAME.class).getMappings(); 


for (org.eclipse.persistence.mappings.DatabaseMapping dm : datamap) { 

    System.out.println(" Attribute name : " + dm.getAttributeName()); // Class field name 
    System.out.println(" Column name : " + dm.getField().getName());  // Database Column name      

} 
  • getFields()返回所有底層列名,這是在類中使用的映射。
  • getMappings()返回類字段名稱與它的數據庫列字段名稱。