您的位置:首页 > 其它

Hibernate根据表名获得实体类名及ID名

2014-07-17 00:00 393 查看
private Map<String, String> mappings;
private Map<String, String> idMappings;
private Map<String, String> idColumns;

public void initMappings() {
if (mappings == null) {
mappings = new HashMap<String, String>();
idMappings = new HashMap<String, String>();
idColumns = new HashMap<String, String>();
SessionFactory factory = this.getSessionFactory();
Map metaMap = factory.getAllClassMetadata();
for (String key : (Set<String>) metaMap.keySet()) {
AbstractEntityPersister classMetadata = (AbstractEntityPersister) metaMap
.get(key);
String tableName = classMetadata.getTableName().toLowerCase();
int index = tableName.indexOf(".");
if (index >= 0) {
tableName = tableName.substring(index + 1);
}
String className = classMetadata.getEntityMetamodel().getName();
String idName = classMetadata.getIdentifierColumnNames()[0];
mappings.put(tableName.toUpperCase(), className);
idColumns.put(tableName.toUpperCase(), idName);
idMappings.put(className,
classMetadata.getIdentifierPropertyName());
}
}
}

public String getEntityName(String tableName) throws Exception {
initMappings();
String entityName = mappings.get(tableName.toUpperCase());
if (entityName == null) {
throw new Exception("表没有映射:" + tableName);
}
return entityName;
}

public String getIdName(String entityName) {
initMappings();
return idMappings.get(entityName);
}

public String getIdColumn(String tableName) {
initMappings();
return idColumns.get(tableName);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  hibernate pb