Reputation: 1
I want to retrieve the java data types of the columns of a table in MySql using hibernate so that I can dynamically convert my input data to corresponding data type while inserting into database.
One way is to read the class-name.hbm.xml
and retrieve the data type information but I want the data types straight from the database and not from any config XMLs as the XMLs can be erroneous.
Another way is using AbstractEntityPersister.getPropertyType(column-name).toString()
but that returns the hibernate data type instead of the corresponding java types.
Is there any way I can achieve this ?
Upvotes: 1
Views: 3840
Reputation: 1
I achieved the required functionality by querying the ColumnsMetaData table from information_schema (a schema containing MySQL's Data Dictionary)
Upvotes: 1
Reputation: 23229
Do the following (bit hacky tho)
Class clazz = ...;
SessionFactory sessionFactory = ...;
ClassMetadata classMetadata = sessionFactory.getClassMetadata( clazz );
// bit of a hack, relies on knowing that SessionFactoryImpl implements Mapping
Mapping mapping = (Mapping)sessionFactory;
for ( String propertyName : classMetadata.getPropertyNames() )
{
Type type = classMetadata.getPropertyType( propertyName );
if ( type.isCollectionType() )
continue;
// TODO: do something with the result
type.sqlTypes( mapping );
}
Upvotes: 5
Reputation: 14671
You can use AbstractEntityPersister.getPropertyColumnNames(...)
, then issue a raw JDBC query on that column and use ResultSet.getColumnType()
Upvotes: 1