Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the entity class name from the table name

I would like to do the reverse of getting the table name from an entity:

I want to get the entity name from a table name, i.e. the name of the entity that is mapped to that table.

Same goes for the db column: how to get the field name of the entity that is mapped to it?

like image 399
Matthieu Napoli Avatar asked Dec 13 '12 16:12

Matthieu Napoli


People also ask

How to define table name in entity class?

The easiest way to set a custom SQL table name is to annotate the entity with @javax. persistence. Table and define its name parameter: @Entity @Table(name = "ARTICLES") public class Article { // ... }

What is @entity annotation in spring boot?

The @Entity annotation specifies that the class is an entity and is mapped to a database table. The @Table annotation specifies the name of the database table to be used for mapping.

How do you map entity and table?

In Spring Data JPA we can map an entity to a specific table by using @Table annotation where we can specify schema and name. But Spring Data JDBC uses a NamingStrategy to map an entity to a table name by converting the entities class name.


1 Answers

Here is what I was able to do, though it's not optimum because it goes through all entity class names registered:

/**
 * @param \Doctrine\ORM\EntityManager $em Entity manager
 * @param string $table Table name
 * @return string Entity class name, null if not found
 */
protected function getClassNameFromTableName($em, $table)
{
    // Go through all the classes
    $classNames = $em->getConfiguration()->getMetadataDriverImpl()->getAllClassNames();
    foreach ($classNames as $className) {
        $classMetaData = $em->getClassMetadata($className);
        if ($table == $classMetaData->getTableName()) {
            return $classMetaData->getName();
        }
    }
    return null;
}

/**
 * @param \Doctrine\ORM\EntityManager $em Entity manager
 * @param string $className
 * @param string $column
 * @return string Field name, null if not found
 */
protected function getFieldNameFromColumnName($em, $className, $column)
{
    $classMetaData = $em->getClassMetadata($className);
    if ($classMetaData) {
        return $classMetaData->getFieldForColumn($column);
    }
    return null;
}
like image 95
Matthieu Napoli Avatar answered Oct 26 '22 02:10

Matthieu Napoli