code为例,在JPA运行时的实体检索表的名字吗? [英] Code example to retrieve table name for an entity in JPA in runtime?

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

问题描述

我要列出我的JPA实体模型的所有数据库表名,但我不能得到正确的实体类!

I want to list all Database Table names for my JPA Entity model, but I can't get the correct Entity class!

EntityManagerFactory factory;
Set<EntityType<?>> entities = factory.getMetamodel().getEntities();
for (EntityType entity: entities) {
    String tableName = entity.getClass().getAnnotation(Table.class).name();
    logger.debug("Entity name  = {}", entity.getName(); //This works
    logger.debug("Entity class = {}", entity.getClass().getName()); //This returns the runtime class of the object, and not the entity class!!
    logger.debug("Entity table = {}", entity.getClass().getAnnotation(Table.class).name()); //Nothing, because it does not find the correct class
}

输出:

Entity name  = PersonEntity
Entity class = org.hibernate.jpa.internal.metamodel.EntityTypeImpl
Entity table = ........ nothing, because this works on the EntityTypeImpl and not on the PersonEnity

如何获得的实体类的表名?谢谢!

推荐答案

确定,因此,如果想与反思做到这一点。它应该是pretty容易,因为这个运行时类必须扩展类。如果它不会扩展你的类,你将无法在应用程序中使用它。

OK, so if want do this with reflection. It should be pretty easy since this runtime class have to extends your class. If it wouldn't extends your class you won't be able to use it in your application.

所以,你必须做类似下面

So you have to do something like below

    String myPackage = "com.company.";
    Class entityClass = y.getClass();
    while (!entityClass.getCanonicalName().startsWith(myPackage)) {
        entityClass = entityClass.getSuperclass();
    }
    Class classInYourPackage = entityClass;

和你应该得到正确的(你的)类。

And you should get correct (your) class.

没测试过,但是这是应该的工作方式。

Not tested, however that's the way it should work.

编辑:不知道什么包会被JPA被分配到这些运行时类。所以,如果code以上不工作与getSuperclass之尝试()方法,你自己的。

Not sure what package will be assigned by JPA to these runtime classes. So if code above doesn't work try with getSuperclass() method on your own.

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

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