在运行时检索 JPA 中实体的表名的代码示例? [英] Code example to retrieve table name for an entity in JPA in runtime?

查看:27
本文介绍了在运行时检索 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

如何获取实体类的表名?

推荐答案

好的,所以如果想用反射来做这件事.这应该很容易,因为这个运行时类必须扩展你的类.如果它不扩展您的类,您将无法在您的应用程序中使用它.

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 会为这些运行时类分配什么包.因此,如果上面的代码不起作用,请尝试自己使用 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.

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

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