JPA/EclipseLink - 检索列名称

Bob*_*ers 3 java orm jpa jpa-2.0

我正在尝试更新我的Java知识,因为我上次在1.4.X版本中使用时...我正在尝试使用1.6.0,特别是Java Persistence API(2.0).

我设法创建了一个实体类.它工作正常,因为我能够存储和检索数据.

但是当我决定使用表的列名填充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;

    ...
}
Run Code Online (Sandbox Code Playgroud)

有没有办法检索列名?

我找到了这篇文章.似乎是一个有效的解决方案,但我认为它可能有更容易/更优雅的东西?我不知道为什么,但我期待已经完成的方法......

TIA,

短发

Boz*_*zho 10

您可以解析列注释:

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

请注意,Column注释是可选的,因此您必须确保已定义注释.如果不是,您将不得不咨询名称翻译机制,这对此来说太过分了.

  • 列注释是可选的 (2认同)

Jam*_*mes 10

在EclipseLink中,您可以获取类的ClassDescriptor并获取其字段(DatabaseField).

em.unwrap(Session.class).getDescriptor(Currency.class).getFields()
Run Code Online (Sandbox Code Playgroud)

您还可以获得所需的映射,表格或其他任何内容.

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