Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/hibernate/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
查找Hibernate实体的主键字段_Hibernate_Primary Key - Fatal编程技术网

查找Hibernate实体的主键字段

查找Hibernate实体的主键字段,hibernate,primary-key,Hibernate,Primary Key,我们是否可以通过编程方式找到Hibernate实体的主键字段(类似于JPA的PersistenceUnitUtil)?看看PersistentClass(您可以通过configuration.getClassMapping()获得它)。根据您的需要,getIdentifierProperty()或getKeyClosureIterator()可能有用 SessionFactory提供了一个调用的方法来获取类的元数据对象(即 要获取实体的标识符属性的名称,请使用 要获取托管实体实例的标识符属性值,

我们是否可以通过编程方式找到Hibernate实体的主键字段(类似于JPA的
PersistenceUnitUtil
)?

看看
PersistentClass
(您可以通过
configuration.getClassMapping()
获得它)。根据您的需要,
getIdentifierProperty()
getKeyClosureIterator()
可能有用

SessionFactory
提供了一个调用的方法来获取类的元数据对象(即

要获取实体的标识符属性的名称,请使用

要获取托管实体实例的标识符属性值,请使用

例如: 假设您有一个从会话加载的托管实体实例:

List<Employee> employeeList = (List<Employee>)session.createQuery("from Employee where gender ='F'").list();
ClassMetadata employeeMeta = session.getSessionFactory().getClassMetadata(Employee.class);
for (Employee employee : employeeList ) {
    System.out.println("Value of the Primary key:" + employeeMeta.getIdentifier(employee , session) );
}
List employeeList=(List)session.createQuery(“from Employee where gender='F').List();
ClassMetadata employeeMeta=session.getSessionFactory().getClassMetadata(Employee.class);
用于(员工:员工列表){
System.out.println(“主键的值:+employeeMeta.getIdentifier(雇员,会话));
}

我意识到这个问题已经有两年多的时间了,并且已经得到了回答,但是它介于Google为“hibernate get primarykey fields”(可能还有其他类似的查询)找到的前10个结果之间,所以我认为在这里添加这些信息很重要

最近,我在一个Java系统上工作,我需要获取一个表的主键,然而,我所拥有的只是Hibernate
Configuration
对象和表的名称

虽然Johanna的答案非常简单,对我很有帮助,但我发现对于具有复合主键的表,它并不像预期的那样有效,因为只找到了组成主键的一个字段

我深入研究了
PersistentClass
属性,找到了一种处理主键(复合键和单键键)两种情况的方法:

/**
*将表的主键映射到一个映射,其中键是表的名称
*组成主键和值的字段是所述的类型名
*田地。
* 
*@param tableName获取主键的名称
*@param Hibernate配置数据库的Hibernate配置
*重要提示:$tableName必须已映射到配置中。
*@返回一个映射,字段名作为键,类型名作为值。
*/
公共静态映射检索PrimaryKeys(字符串表名、配置hibernateConfiguration){
hibernateConfiguration.buildMappings();
HashMap primaryKeys=新HashMap();
PersistentClass tableMapping=hibernateConfiguration.getClassMapping(tableName);
对象tableIdentifier=tableMapping.getIdentifier();
if(SimpleValue的tableIdentifier实例){
//只要标识符是SimpleValue,就意味着该表只有一个PrimaryKey。
//此时,假设主键是使用映射XML文件中的元素映射的。
//我们在下面的列中进行了迭代,因为这是一种更安全的处理方法。
SimpleValue tableIdentifierValue=(SimpleValue)tableIdentifier;
迭代器PrimaryKey迭代器=tableIdentifierValue.getColumnIterator();
while(primaryKey迭代器.hasNext()){
列primaryKey=(列)primaryKey迭代器.next();
SimpleValue primaryKeyValue=(SimpleValue)primaryKey.getValue();
put(primaryKey.getName(),primaryKeyValue.getTypeName());
}
}
else if(组件的tableIdentifier实例)
{
//只要标识符是一个组件,就意味着该表有一个复合主键。
//此时,假设主键是使用映射XML文件中的元素映射的
组件标识符=(组件)表标识符;
迭代器identifierIterator=标识符。getPropertyIterator();
while(IdentifierInterator.hasNext()){
属性标识符=(属性)IdentifierInterator.next();
SimpleValue=(SimpleValue)标识符。getValue();
primaryKeys.put(identifier.getName(),value.getTypeName());
}
}
其他的
{
//如果程序达到这一点,就意味着Hibernate讨厌您,还有第三种未知的方法可以声明和获取表的主键。
}
返回主密钥;
}

我必须补充一点,Java不是我的专长,Hibernate也不是,所以可能有更好、更简洁的方法来处理这个问题(至少我希望是这样),但我找不到它。

因为我刚刚输入了我自己的答案,我已经找到了答案,并且按照你(@KenChan)在这里所说的方式,我看到了你的帖子!谢谢这里的会话是什么类型的?我的代码中没有类似的内容(没有使用getSessionFactory)
List<Employee> employeeList = (List<Employee>)session.createQuery("from Employee where gender ='F'").list();
ClassMetadata employeeMeta = session.getSessionFactory().getClassMetadata(Employee.class);
for (Employee employee : employeeList ) {
    System.out.println("Value of the Primary key:" + employeeMeta.getIdentifier(employee , session) );
}
/**
 * Maps a table's primary key to a Map<String, String> where the keys are the names of
 * the fields that compose the primary key and the values are the type names of said
 * fields.
 * 
 * @param tableName The name of the which for which the primary keys will be gotten
 * @param hibernateConfiguration The Hibernate configuration for the database
 *     IMPORTANT: $tableName must be already mapped in the configuration.
 * @returns A map with the fields names as keys and their types' names as values.
 */
public static Map<String, String> retrievePrimaryKeys(String tableName, Configuration hibernateConfiguration) {
    hibernateConfiguration.buildMappings();

    HashMap<String, String> primaryKeys = new HashMap<>();
    PersistentClass tableMapping = hibernateConfiguration.getClassMapping(tableName);

    Object tableIdentifier =  tableMapping.getIdentifier();

    if(tableIdentifier instanceof SimpleValue) {

        // Whenever the identifier is a SimpleValue, it means that the table has only one PrimaryKey. 
        // At this point, it's assumed that the primary key was mapped using the <id> element in the mapping XML file.
        // We iterate over the columns below, because it's a safer way of handling this thing.

        SimpleValue tableIdentifierValue = (SimpleValue) tableIdentifier;
        Iterator primaryKeysIterator = tableIdentifierValue.getColumnIterator();

        while(primaryKeysIterator.hasNext()) {
            Column primaryKey = (Column) primaryKeysIterator.next();
            SimpleValue primaryKeyValue = (SimpleValue) primaryKey.getValue();
            primaryKeys.put(primaryKey.getName(), primaryKeyValue.getTypeName());
        }
    }
    else if (tableIdentifier instanceof Component)
    {
        // Whenever the identifier is a Component, it means that the table has a composite primary key.
        // At this point, it's assumed that the primary key was mapped using the <composite-id> element in the mapping XML file

        Component identifiers = (Component) tableIdentifier;
        Iterator identifierIterator = identifiers.getPropertyIterator();

        while(identifierIterator.hasNext()) {
            Property identifier = (Property) identifierIterator.next();
            SimpleValue value = (SimpleValue) identifier.getValue();

            primaryKeys.put(identifier.getName(), value.getTypeName());
        }
    }
    else
    {
        // If the program reaches this point, it means that Hibernate hates you and there's a third unknown way of declaring and getting a table's primary key.
    }

    return primaryKeys;
}