简体   繁体   English

如何使用Hibernate从数据库中检索列的Java数据类型?

[英]How to retrieve the java data types of columns from the database using Hibernate?

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. 我想使用休眠方式在MySql中检索表的列的Java数据类型,以便在插入数据库时​​可以将输入数据动态转换为相应的数据类型。

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. 一种方法是读取class-name.hbm.xml并检索数据类型信息,但我希望直接从数据库而不是从任何配置XML读取数据类型,因为XML可能是错误的。

Another way is using AbstractEntityPersister.getPropertyType(column-name).toString() but that returns the hibernate data type instead of the corresponding java types. 另一种方法是使用AbstractEntityPersister.getPropertyType(column-name).toString()但是它将返回休眠数据类型,而不是相应的java类型。

Is there any way I can achieve this ? 有什么办法可以实现?

Do the following (bit hacky tho) 执行以下操作(位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 );
    }

您可以使用AbstractEntityPersister.getPropertyColumnNames(...) ,然后对该列执行原始JDBC查询,并使用ResultSet.getColumnType()

我通过从information_schema (包含MySQL 数据字典的模式)中查询ColumnsMetaData表来实现了所需的功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用进度数据库从备忘录字段中检索Java中的数据 - How to retrieve data in java from memo field using progress database 使用休眠模式将Json数据存储到Mysql 5.7数据库/从Mysql 5.7数据库获取Json数据 - Store/Retrieve Json data to/from Mysql 5.7 database using hibernate 如何在Hibernate中使用DAO方法从数据库中检索,更新,删除数据 - How to retrieve,update,delete data from database using DAO method in Hibernate hibernate如何从现有数据库视图中检索数据? - How hibernate retrieve data from existing database view? java如何从数据库中检索数据 - java how retrieve data from database 如何在Java中正确地从数据库检索数据 - how to retrieve data from database correctly in java 如何通过使用Spring 2.0和Hibernate SpringMVC从数据库中检索记录 - how to retrieve the record from database by using spring 2.0 with hibernate springMVC 如何从数据库中检索实例并使用struts2和hibernate显示它? - How to retrieve an instance from the database and display it using struts2 and hibernate? 如何使用Hibernate检查值并从数据库中检索它(如果存在)? - How to check the value and retrieve it from database if it exists using Hibernate? 如何从Java Spring中的Hibernate双向OneToMany ManyToOne中检索数据 - How to retrieve data from Hibernate bidirectional OneToMany ManyToOne in Java Spring
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM