简体   繁体   中英

Get table column names in Hibernate

I am using hibernate Criteria class to get all records of table :

Criteria criteria = session.createCriteria(AppTaskConfig.class)

I would like to get column names also as I need to convert result set into JSON format.

To get the column names , first you need to find the properties of the entity using org.hibernate.metadata.ClassMetadata :

ClassMetadata classMetadata = sessionFactory.getClassMetadata(AppTaskConfig.class);
String[] propertyNames = classMetadata.getPropertyNames();

where propertyNames is an array of Strings representing the property names of AppTaskConfig .

Now using Hibernate org.hibernate.cfg.Configuration object you can find the column names of the properties :

for (String property : propertyNames) {
    Configuration configuration = sessionFactoryBean.getConfiguration();
    PersistentClass persistentClass = configuration
                    .getClassMapping(Details.class.getName());
    String columnName = ((Column) persistentClass.getProperty(property)
                    .getColumnIterator().next()).getName();
}

An easier way to get column name with hibernate 5

final AbstractEntityPersister classMetadata = (AbstractEntityPersister) sessionFactory.getClassMetadata(clazz)
final String[] names = classMetadata.getPropertyColumnNames(property)

With hibernate 4, I do just like @Debojit Saikia

What are column names of entity? Entity could use some of the table's columns and don't have fields for other.

Entity could extend another Entity class so fields of the Entity class are represented by columns from different tables.

You can run native SQl query and see table columns.

String[] columnNames = getSessionFactory().getClassMetadata(Employee.class).getPropertyNames();

  org.hibernate.type.Type[] columnTypes = getSessionFactory().getClassMetadata(Employee.class).getPropertyTypes();

try this this is work properly...

You can use Reflection API to access to declared JPA annotations of a field/getter like Column o JoinColumn.

import javax.persistence.Column;
import javax.persistence.JoinColumn;

// get declared field
Field field = persistentClass.getDeclaredField("property");

// get declared method
Method method = persistentClass.getMethod("get"+property.substring(0,1).toUpper()+property.substring(1)));

// access to declared annotations or field or method to find Column or JoinColumn

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM