Code example to retrieve table name for an entity in JPA in runtime?

前端 未结 2 1247
悲&欢浪女
悲&欢浪女 2021-01-15 23:51

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

        
2条回答
  •  醉酒成梦
    2021-01-16 00:19

    To answer this question, we must realize that the JPA runtime type wraps the original @Entity annotated POJO. A simple test with the non-runtime class will show that the Table name is accessible:

    System.out.println("Table_Name: " + MyEntity.class.getAnnotation(Table.class).name());
    

    So the trick here is to get access to the correct entity class reference, and then call the desired functions from there.

    Referring to the API for EntityTypeImpl, we can see that it inherits from AbstractType, which provides the method "getJavaType()", which returns a reference to the underlying entity class. With this knowledge, we can write the following function to get the every Entity Class associated with the current session, as well as every Table name associated with every entity.

    protected void testFunc() {
        Metamodel metamodel = entityManager.getMetamodel();
        for (EntityType e : metamodel.getEntities()) {
            Class entityClass = e.getJavaType();
            String entityTableName = entityClass.getAnnotation(Table.class).name();
            System.out.println("Table_Name: " + entityTableName);
        }
    }
    

提交回复
热议问题