如何在运行时通过表名在JPA中检索实体? [英] How to retrieve an entity in JPA by table name at runtime?

查看:184
本文介绍了如何在运行时通过表名在JPA中检索实体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以通过实体的本地表名来确定实体类名?

旧代码的某些部分 (在此示例中为CUSM_LANGUAGE),我需要 找到实体类名 >(LanguageEntity)

Some part of legacy code does only have a String value of the table (CUSM_LANGUAGE in this example), and I need to find the entity class name (LanguageEntity)

@Entity
@Table(name = "CUSM_LANGUAGE")
public class LanguageEntity implements java.io.Serializable {
    private static final long serialVersionUID = 1L;
    @Column(name = "LANG_DESCRIPTION")
    private String description = null;
    ....


推荐答案

在JPA 2.0中,您有类: http://docs.oracle.com/javaee/6/api/javax/persistence/EntityManagerFactory.html

In JPA 2.0 you have class: http://docs.oracle.com/javaee/6/api/javax/persistence/EntityManagerFactory.html

这个类有getMetamodel()方法,我希望包含你的数据库的所有信息。

This class has getMetamodel() method which I expect to contains all information about your database.

在Metamodel( http://docs.oracle.com/javaee/6/api/javax/持久化/元模型/ Metamodel.html )你有getEntities(),这是我们得到的:EntityType

In Metamodel (http://docs.oracle.com/javaee/6/api/javax/persistence/metamodel/Metamodel.html) you have getEntities() that's how we get: EntityType

我不知道如何从EntityType获得有关表它正在使用。但是,即使它不是直接的可能(我怀疑),你可以做如下所述。

I'm not sure how get from EntityType information about table it is using. But even it's not directly possible (which I doubt) you can do it as described below.

因为你有遗留代码,我希望你有JPA< 2.0,它没有这个getMetamodel方法。这就是为什么你可以得到实体的信息强烈取决于你使用的特定JPA。

Because you have legacy code I expect you have JPA < 2.0 which doesn't have this getMetamodel method. That's why informations you can get about entities strongly depends on specific JPA you're using.

但是如果你有很多类,你关心(你可以创建这个列表你可以自己创建索引:

However if you have bunch of classes you care about (and you can create this list easily) you can create index on your own:

String tableNameOfEntityClass = LanguageEntity.class.getAnnotation(Table.class).name();

所以你可以把所有你关心的类列出,然后创建关键tableName和值引用类。

So you can put all classes you care to list and then create map with key tableName and value refering class.

当然,如果没有我上面描述的Metamodel,它也不是很有用,因为你可以创建准备好的映射,而不是List和实体类。

Of course it's not very useful without Metamodel which I described above because as well you can create ready map instead of List with entity classes.

这篇关于如何在运行时通过表名在JPA中检索实体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆