Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the table name from the model in Hibernate

Tags:

java

hibernate

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.

like image 227
Can Berk Güder Avatar asked Mar 11 '09 12:03

Can Berk Güder


People also ask

How to specify table name in jpa?

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 { // ... }

How can I get all data from a table in hibernate?

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.

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.


2 Answers

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(); } 
like image 93
FoxyBOA Avatar answered Sep 18 '22 17:09

FoxyBOA


If you're using the Table annotation you could do something like this:

Table table = Entity.class.getAnnotation(Table.class); String tableName = table.name(); 
like image 24
Alex Rockwell Avatar answered Sep 18 '22 17:09

Alex Rockwell