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?
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 { // ... }
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.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With