本帖最后由 szxzm 于 2010-09-07 15:41:17 编辑

解决方案 »

  1.   

    自己解决了,又是修改HIBERNATE源码,在org.hibernate.cfg.Mappings类中修改addClass方法,把判断去除public void addClass(PersistentClass persistentClass) throws MappingException {
    Object old = classes.put( persistentClass.getEntityName(), persistentClass );
    //去除这个判断,以重复修改加载
    //if ( old!=null ) {
    // throw new DuplicateMappingException( "class/entity", persistentClass.getEntityName() );
    //}
    }
    暂还没发现其它问题
      

  2.   

    以上方法有误,还是要动大手术~附上最终解决方案:一、修改SessionFactoryImpl.java如下:public SessionFactoryImpl(
    Configuration cfg,
            Mapping mapping,
            Settings settings,
            EventListeners listeners)
    throws HibernateException { log.info("building session factory"); this.properties = new Properties();
    this.properties.putAll( cfg.getProperties() );
    this.interceptor = cfg.getInterceptor();
    this.settings = settings;
    this.sqlFunctionRegistry = new SQLFunctionRegistry(settings.getDialect(), cfg.getSqlFunctions());
            this.eventListeners = listeners;
            this.filters = new HashMap();
    this.filters.putAll( cfg.getFilterDefinitions() ); if ( log.isDebugEnabled() ) {
    log.debug("Session factory constructed with filter configurations : " + filters);
    } if ( log.isDebugEnabled() ) {
    log.debug(
    "instantiating session factory with properties: " + properties
    );
    } // Caches
    settings.getCacheProvider().start( properties ); //Generators: identifierGenerators = new HashMap();
    Iterator classes = cfg.getClassMappings();
    while ( classes.hasNext() ) {
    PersistentClass model = (PersistentClass) classes.next();
    if ( !model.isInherited() ) {
    IdentifierGenerator generator = model.getIdentifier().createIdentifierGenerator(
    settings.getDialect(),
            settings.getDefaultCatalogName(),
            settings.getDefaultSchemaName(),
            (RootClass) model
    );
    identifierGenerators.put( model.getEntityName(), generator );
    }
    } //Persisters: Map caches = new HashMap();
    entityPersisters = new HashMap();
    Map classMeta = new HashMap();
    classes = cfg.getClassMappings();
    while ( classes.hasNext() ) {
    PersistentClass model = (PersistentClass) classes.next();
    model.prepareTemporaryTables( mapping, settings.getDialect() );
    String cacheRegion = model.getRootClass().getCacheRegionName();
    CacheConcurrencyStrategy cache = (CacheConcurrencyStrategy) caches.get(cacheRegion);
    if (cache==null) {
    cache = CacheFactory.createCache(
    model.getCacheConcurrencyStrategy(),
            cacheRegion,
            model.isMutable(),
            settings,
            properties
    );
    if (cache!=null) {
    caches.put(cacheRegion, cache);
    allCacheRegions.put( cache.getRegionName(), cache.getCache() );
    }
    }
    EntityPersister cp = PersisterFactory.createClassPersister(model, cache, this, mapping);
    if ( cache != null && cache.getCache() instanceof OptimisticCache ) {
    ( ( OptimisticCache ) cache.getCache() ).setSource( cp );
    }
    entityPersisters.put( model.getEntityName(), cp );
    classMeta.put( model.getEntityName(), cp.getClassMetadata() );
    }
    // TODO 为了动态添加数据表绑定修改
    // classMetadata = Collections.unmodifiableMap(classMeta);
    classMetadata = new HashMap();
    classMetadata.putAll(classMeta); Map tmpEntityToCollectionRoleMap = new HashMap();
    collectionPersisters = new HashMap();
    Iterator collections = cfg.getCollectionMappings();
    while ( collections.hasNext() ) {
    Collection model = (Collection) collections.next();
    CacheConcurrencyStrategy cache = CacheFactory.createCache(
    model.getCacheConcurrencyStrategy(),
         model.getCacheRegionName(),
         model.isMutable(),
         settings,
         properties
    );
    if ( cache != null ) {
    allCacheRegions.put( cache.getRegionName(), cache.getCache() );
    }
    CollectionPersister persister = PersisterFactory.createCollectionPersister(cfg, model, cache, this);
    collectionPersisters.put( model.getRole(), persister.getCollectionMetadata() );
    Type indexType = persister.getIndexType();
    if ( indexType != null && indexType.isAssociationType() && !indexType.isAnyType() ) {
    String entityName = ( ( AssociationType ) indexType ).getAssociatedEntityName( this );
    Set roles = ( Set ) tmpEntityToCollectionRoleMap.get( entityName );
    if ( roles == null ) {
    roles = new HashSet();
    tmpEntityToCollectionRoleMap.put( entityName, roles );
    }
    roles.add( persister.getRole() );
    }
    Type elementType = persister.getElementType();
    if ( elementType.isAssociationType() && !elementType.isAnyType() ) {
    String entityName = ( ( AssociationType ) elementType ).getAssociatedEntityName( this );
    Set roles = ( Set ) tmpEntityToCollectionRoleMap.get( entityName );
    if ( roles == null ) {
    roles = new HashSet();
    tmpEntityToCollectionRoleMap.put( entityName, roles );
    }
    roles.add( persister.getRole() );
    }
    }
    // TODO 为了动态添加数据表绑定修改
    // collectionMetadata = Collections.unmodifiableMap(collectionPersisters);
    collectionMetadata = new HashMap();
    collectionMetadata.putAll(collectionPersisters);

    Iterator itr = tmpEntityToCollectionRoleMap.entrySet().iterator();
    while ( itr.hasNext() ) {
    final Map.Entry entry = ( Map.Entry ) itr.next();
    entry.setValue( Collections.unmodifiableSet( ( Set ) entry.getValue() ) );
    }
    // TODO 为了动态添加数据表绑定修改
    // collectionRolesByEntityParticipant = Collections.unmodifiableMap(tmpEntityToCollectionRoleMap);
    collectionRolesByEntityParticipant = new HashMap();
    collectionRolesByEntityParticipant.putAll(tmpEntityToCollectionRoleMap); //Named Queries:
    namedQueries = new HashMap( cfg.getNamedQueries() );
    namedSqlQueries = new HashMap( cfg.getNamedSQLQueries() );
    sqlResultSetMappings = new HashMap( cfg.getSqlResultSetMappings() );
    imports = new HashMap( cfg.getImports() ); // after *all* persisters and named queries are registered
    Iterator iter = entityPersisters.values().iterator();
    while ( iter.hasNext() ) {
    ( (EntityPersister) iter.next() ).postInstantiate();
    }
    iter = collectionPersisters.values().iterator();
    while ( iter.hasNext() ) {
    ( (CollectionPersister) iter.next() ).postInstantiate();
    } //JNDI + Serialization: name = settings.getSessionFactoryName();
    try {
    uuid = (String) UUID_GENERATOR.generate(null, null);
    }
    catch (Exception e) {
    throw new AssertionFailure("Could not generate UUID");
    }
    SessionFactoryObjectFactory.addInstance(uuid, name, this, properties); log.debug("instantiated session factory"); if ( settings.isAutoCreateSchema() ) {
    new SchemaExport( cfg, settings ).create( false, true );
    }
    if ( settings.isAutoUpdateSchema() ) {
    new SchemaUpdate( cfg, settings ).execute( false, true );
    }
    if ( settings.isAutoValidateSchema() ) {
    new SchemaValidator( cfg, settings ).validate();
    }
    if ( settings.isAutoDropSchema() ) {
    schemaExport = new SchemaExport( cfg, settings );
    } if ( settings.getTransactionManagerLookup()!=null ) {
    log.debug("obtaining JTA TransactionManager");
    transactionManager = settings.getTransactionManagerLookup().getTransactionManager(properties);
    }
    else {
    if ( settings.getTransactionFactory().isTransactionManagerRequired() ) {
    throw new HibernateException("The chosen transaction strategy requires access to the JTA TransactionManager");
    }
    transactionManager = null;
    } currentSessionContext = buildCurrentSessionContext(); if ( settings.isQueryCacheEnabled() ) {
    updateTimestampsCache = new UpdateTimestampsCache(settings, properties);
    queryCache = settings.getQueryCacheFactory()
            .getQueryCache(null, updateTimestampsCache, settings, properties);
    queryCaches = new HashMap();
    allCacheRegions.put( updateTimestampsCache.getRegionName(), updateTimestampsCache.getCache() );
    allCacheRegions.put( queryCache.getRegionName(), queryCache.getCache() );
    }
    else {
    updateTimestampsCache = null;
    queryCache = null;
    queryCaches = null;
    } //checking for named queries
    if ( settings.isNamedQueryStartupCheckingEnabled() ) {
    Map errors = checkNamedQueries();
    if ( !errors.isEmpty() ) {
    Set keys = errors.keySet();
    StringBuffer failingQueries = new StringBuffer( "Errors in named queries: " );
    for ( Iterator iterator = keys.iterator() ; iterator.hasNext() ; ) {
    String queryName = ( String ) iterator.next();
    HibernateException e = ( HibernateException ) errors.get( queryName );
    failingQueries.append( queryName );
    if ( iterator.hasNext() ) {
    failingQueries.append( ", " );
    }
    log.error( "Error in named query: " + queryName, e );
    }
    throw new HibernateException( failingQueries.toString() );
    }
    } //stats
    getStatistics().setStatisticsEnabled( settings.isStatisticsEnabled() ); // EntityNotFoundDelegate
    EntityNotFoundDelegate entityNotFoundDelegate = cfg.getEntityNotFoundDelegate();
    if ( entityNotFoundDelegate == null ) {
    entityNotFoundDelegate = new EntityNotFoundDelegate() {
    public void handleEntityNotFound(String entityName, Serializable id) {
    throw new ObjectNotFoundException( id, entityName );
    }
    };
    }
    this.entityNotFoundDelegate = entityNotFoundDelegate;
    }
      

  3.   

    二、加入如下方法:public void registerPersistentEntitys() {
    Configuration cfg = HibernateSessionFactory.getConfiguration();
    SessionFactory factory = HibernateSessionFactory.getSessionFactory();
    Mapping mapping = cfg.getMapping();


    Iterator classes = cfg.getClassMappings();
    while (classes.hasNext()) {
    PersistentClass model = (PersistentClass) classes.next();
    _AddPersisterClass(model, mapping);
    } // Collections:
    Iterator collections = cfg.getCollectionMappings();
    while (collections.hasNext()) {
    Collection model = (Collection) collections.next();
    if (!collectionPersisters.containsKey(model.getRole())) {
    _AddCollection(model);
    }
    } // Named Queries:
    namedQueries.putAll(cfg.getNamedQueries());
    namedSqlQueries.putAll(cfg.getNamedSQLQueries());
    sqlResultSetMappings.putAll(cfg.getSqlResultSetMappings());
    imports.putAll(cfg.getImports()); // after *all* persisters and named queries are registered
    Iterator iter = entityPersisters.values().iterator();
    while (iter.hasNext()) {
    ((EntityPersister) iter.next()).postInstantiate();
    }
    iter = collectionPersisters.values().iterator();
    while (iter.hasNext()) {
    ((CollectionPersister) iter.next()).postInstantiate();
    }
    }

    private void _AddPersisterClass(PersistentClass persistentClass,
    Mapping mapping) {
    String entityName = persistentClass.getEntityName(); // Generators
    if (!persistentClass.isInherited()) {
    IdentifierGenerator generator = persistentClass.getIdentifier()
    .createIdentifierGenerator(settings.getDialect(),
    settings.getDefaultCatalogName(),
    settings.getDefaultSchemaName(),
    (RootClass) persistentClass);
    if (!identifierGenerators.containsKey(entityName))
    identifierGenerators.put(entityName, generator);
    } // Cache
    persistentClass.prepareTemporaryTables(mapping, settings.getDialect());
    String cacheRegion = persistentClass.getRootClass()
    .getCacheRegionName(); CacheConcurrencyStrategy cache = CacheFactory.createCache(
    persistentClass.getCacheConcurrencyStrategy(), cacheRegion,
    persistentClass.isMutable(), settings, properties);
    if (cache != null)
    allCacheRegions.put(cache.getRegionName(), cache.getCache()); // Persister
    EntityPersister cp = PersisterFactory.createClassPersister(
    persistentClass, cache, this, mapping);
    if (cache != null && cache.getCache() instanceof OptimisticCache) {
    ((OptimisticCache) cache.getCache()).setSource(cp);
    }
    entityPersisters.put(entityName, cp);
    classMetadata.put(entityName, cp.getClassMetadata());
    }

    private void _AddCollection(Collection model) {
    Configuration cfg = HibernateSessionFactory.getConfiguration();
    String role = model.getRole();
    CacheConcurrencyStrategy cache = CacheFactory.createCache(model
    .getCacheConcurrencyStrategy(), model.getCacheRegionName(),
    model.isMutable(), settings, properties);
    if (cache != null) {
    allCacheRegions.put(cache.getRegionName(), cache.getCache());
    }
    CollectionPersister persister = PersisterFactory
    .createCollectionPersister(cfg, model, cache, this);
    collectionPersisters.put(role, persister.getCollectionMetadata());
    collectionMetadata.put(role, persister.getCollectionMetadata());
    Type indexType = persister.getIndexType();
    if (indexType != null && indexType.isAssociationType()
    && !indexType.isAnyType()) {
    String entityName = ((AssociationType) indexType)
    .getAssociatedEntityName(this);
    Set roles = (Set) collectionRolesByEntityParticipant
    .get(entityName);
    if (roles == null) {
    roles = new HashSet();
    collectionRolesByEntityParticipant.put(entityName, roles);
    }
    roles.add(persister.getRole());
    }
    Type elementType = persister.getElementType();
    if (elementType.isAssociationType() && !elementType.isAnyType()) {
    String entityName = ((AssociationType) elementType)
    .getAssociatedEntityName(this);
    Set roles = (Set) collectionRolesByEntityParticipant
    .get(entityName);
    if (roles == null) {
    roles = new HashSet();
    collectionRolesByEntityParticipant.put(entityName, Collections
    .unmodifiableSet(roles)); }
    roles.add(persister.getRole());
    }
    }
    三、然后,在Configuration.java中加入如下方法public Configuration addOrReplaceURL(URL url) throws MappingException {
    if (log.isDebugEnabled()) {
    log.debug("Reading mapping document from URL:"
    + url.toExternalForm());
    }
    try {
    addOrReplaceInputStream(url.openStream());
    } catch (InvalidMappingException e) {
    throw new InvalidMappingException("URL", url.toExternalForm(), e
    .getCause());
    } catch (Exception e) {
    throw new InvalidMappingException("URL", url.toExternalForm(), e);
    }
    return this;
    }

    private Configuration addOrReplaceInputStream(InputStream xmlInputStream) {
    try {
    List errors = new ArrayList();
    org.dom4j.Document doc = xmlHelper.createSAXReader(
    "XML InputStream", errors, entityResolver).read(
    new InputSource(xmlInputStream));
    if (errors.size() != 0) {
    throw new InvalidMappingException("invalid mapping", null,
    (Throwable) errors.get(0));
    }
    addOrReplace(doc);
    return this;
    } catch (DocumentException e) {
    throw new InvalidMappingException("input stream", null, e);
    } finally {
    try {
    xmlInputStream.close();
    } catch (IOException ioe) {
    log.warn("Could not close input stream", ioe);
    }
    }
    }

    private void addOrReplace(org.dom4j.Document doc) {
    Element hmNode = doc.getRootElement();
    Iterator rootChildren = hmNode.elementIterator();
    while (rootChildren.hasNext()) {
    final Element element = (Element) rootChildren.next();
    final String elementName = element.getName();
    if ("class".equals(elementName)) {
    String entityName = element.attributeValue("entity-name");
    if (entityName == null) {
    entityName = element.attributeValue("name");
    if (entityName == null) {
    throw new MappingException(
    "Unable to determine entity name");
    }
    }
    classes.remove(entityName);
    }
    }
    HbmBinder.bindRoot(doc, createMappings(), CollectionHelper.EMPTY_MAP);
    }
    四、开始调用HIBERNATE动态加载HBMConfiguration config = HibernateSessionFactory.getConfiguration();
    SessionFactory factory = HibernateSessionFactory.getSessionFactory();
    URL url = this.getClass().getResource("/hbm/org.hbm.xml");
    if (url != null)
    config.addOrReplaceURL(url);
    ((SessionFactoryImpl) factory).registerPersistentEntitys();
    new SchemaUpdate(config, ((SessionFactoryImpl) factory).getSettings())
    .execute(false, true);
    如何去生成HBM就不讲了,比较简单了