JavaDeveloper1
JavaDeveloper1

Reputation: 43

How to get entity class by database table name?

Is it possible to get the Entity class Name from table Name? I am using JPA.

I have the table name. I am able to get the primary keys of the table. Now i want to retrieve a tuple from the table. I need the tuple in the form of entity object or in the form of string array.

Thanks in advance.

Upvotes: 2

Views: 1130

Answers (1)

Jasper de Vries
Jasper de Vries

Reputation: 20158

Since Java Persistence 2.0 you can use Metamodel to do so:

public Class<?> getTypeForTableName(String tableName) {
  for (EntityType<?> entityType : getEntityManager().getMetamodel().getEntities()) {
    if (entityType.getJavaType().getAnnotation(Table.class).name().equals(tableName)) {
      return entityType.getJavaType();
    }
  }
  return null;
}

Upvotes: 4

Related Questions