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 ?

3 Answers 3

5

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 );
    }
Sign up to request clarification or add additional context in comments.

Comments

1

You can use AbstractEntityPersister.getPropertyColumnNames(...), then issue a raw JDBC query on that column and use ResultSet.getColumnType()

Comments

1

I achieved the required functionality by querying the ColumnsMetaData table from information_schema (a schema containing MySQL's Data Dictionary)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.