How do I get the table name for a model in Hibernate?
Apparently there used to be a getTableName()
method in ClassMetadata
, but it's been removed.
There's a getClassMapping(String entityName)
method in Configuration
, but I don't know how I can (or if I should) use Configuration from within my DAO implementation.
My DAO implementation is a subclass of HibernateGeneralGenericDao.
UPDATE: It turns out I can do what I'm trying to do without the table name. However, I will keep the question open (and try the answers as they come) for the sake of reference.
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 { // ... }
JPQL provides a simple and straightforward way to get all entities from a table. Our Hibernate session's createQuery() method receives a typed query string as the first argument and the entity's type as the second. We execute the query with a call to the getResultList() method which returns the results as a typed List.
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.
It's a bit weird but it works:
ClassMetadata hibernateMetadata = sessionFactory.getClassMetadata(pClassName); if (hibernateMetadata == null) { return; } if (hibernateMetadata instanceof AbstractEntityPersister) { AbstractEntityPersister persister = (AbstractEntityPersister) hibernateMetadata; String tableName = persister.getTableName(); String[] columnNames = persister.getKeyColumnNames(); }
If you're using the Table annotation you could do something like this:
Table table = Entity.class.getAnnotation(Table.class); String tableName = table.name();
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