Hibernate获取映射实体的所有外键

我需要为所有映射的hibernate实体获取外键的列名。 有谁知道这是怎么做到的吗? 我试过sessionFactory.getClassMetadata – 我可以看到所有实体的所有属性名称和类型,但我找不到有关外键的信息。 有谁有想法吗? 我可能不使用直接数据库查询 – 我必须从hibernate元数据中提取它。

您可以使用Java Reflection:

 // Loop through joined columns that has @JoinColumn annotation for (Method method : testClass.getMethods()) { if (method.isAnnotationPresent(JoinColumn.class)) { // name parameter is foreign key String foreignKey = method.getAnnotation(JoinColumn.class).name; // if the referencedColumnName is explicitly defined String foreignKey = method.getAnnotation(JoinColumn.class).referencedColumnName; } }