annotationconfiguration.java

来自「hibernate3.2.6源码和jar包」· Java 代码 · 共 1,029 行 · 第 1/3 页

JAVA
1,029
字号
			}		}		boolean applyOnDdl = getProperties().getProperty(				"hibernate.validator.apply_to_ddl", //org.hibernate.validator.Environment.APPLY_TO_DDL				"true" )				.equalsIgnoreCase( "true" );		//TODO search for the method only once and cache it?		Constructor validatorCtr = null;		Method applyMethod = null;		try {			Class classValidator = ReflectHelper.classForName( "org.hibernate.validator.ClassValidator", this.getClass() );			Class messageInterpolator = ReflectHelper.classForName( "org.hibernate.validator.MessageInterpolator", this.getClass() );			validatorCtr = classValidator.getDeclaredConstructor( new Class[] {					Class.class, ResourceBundle.class, messageInterpolator, Map.class, ReflectionManager.class			}			);			applyMethod = classValidator.getMethod( "apply", PersistentClass.class );		}		catch (ClassNotFoundException e) {			if ( !isValidatorNotPresentLogged ) {				log.info( "Hibernate Validator not found: ignoring" );			}			isValidatorNotPresentLogged = true;		}		catch (NoSuchMethodException e) {			throw new AnnotationException( e );		}		if ( applyMethod != null && applyOnDdl ) {			for (PersistentClass persistentClazz : (Collection<PersistentClass>) classes.values()) {				//integrate the validate framework				String className = persistentClazz.getClassName();				if ( StringHelper.isNotEmpty( className ) ) {					try {						Object validator = validatorCtr.newInstance(								ReflectHelper.classForName( className ), null, null, null, reflectionManager						);						applyMethod.invoke( validator, persistentClazz );					}					catch (Exception e) {						log.warn( "Unable to apply constraints on DDL for " + className, e );					}				}			}		}	}	private void processFkSecondPassInOrder() {		log.debug( "processing fk mappings (*ToOne and JoinedSubclass)" );		Iterator iter = secondPasses.iterator();		/* We need to process FKSecond pass trying to resolve any		 * graph circularity (ie PK made of a many to one linking to		 * an entity having a PK made of a ManyToOne ...		 */		SortedSet<FkSecondPass> fkSecondPasses = new TreeSet<FkSecondPass>(				new Comparator<FkSecondPass>() {					//The comparator implementation has to respect the compare=0 => equals() = true for sets					public int compare(FkSecondPass f1, FkSecondPass f2) {						int compare = f1.getValue().getTable().getQuotedName().compareTo(								f2.getValue().getTable().getQuotedName()						);						if ( compare == 0 ) {							//same table, we still need to differenciate true equality							if ( f1.hashCode() < f2.hashCode() ) {								compare = -1;							}							else if ( f1.hashCode() == f2.hashCode() ) {								compare = 0;							}							else {								compare = 1;							}						}						return compare;					}				}		);		while ( iter.hasNext() ) {			SecondPass sp = (SecondPass) iter.next();			//do the second pass of fk before the others and remove them			if ( sp instanceof FkSecondPass ) {				fkSecondPasses.add( (FkSecondPass) sp );				iter.remove();			}		}		if ( fkSecondPasses.size() > 0 ) {			Map<String, Set<String>> isADependencyOf = new HashMap<String, Set<String>>();			List orderedFkSecondPasses = new ArrayList( fkSecondPasses.size() );			List endOfQueueFkSecondPasses = new ArrayList( fkSecondPasses.size() );			List orderedTable = new ArrayList( fkSecondPasses.size() );			Iterator it = fkSecondPasses.iterator();			while ( it.hasNext() ) {				FkSecondPass sp = (FkSecondPass) it.next();				String referenceEntityName = sp.getReferencedEntityName();				PersistentClass classMapping = getClassMapping( referenceEntityName );				if ( sp.isInPrimaryKey() ) {					String dependentTable = classMapping.getTable().getQuotedName();					if ( !isADependencyOf.containsKey( dependentTable ) ) {						isADependencyOf.put( dependentTable, new HashSet<String>() );					}					String table = sp.getValue().getTable().getQuotedName();					isADependencyOf.get( dependentTable ).add( table );					int beAfter = orderedTable.indexOf( dependentTable );					int beBefore = orderedFkSecondPasses.size();					Set<String> dependencies = isADependencyOf.get( table );					if ( dependencies != null ) {						for (String tableDep : dependencies) {							//for each declared dependency take the lowest index							int index = orderedTable.indexOf( tableDep );							//index = -1 when we have a self dependency							beBefore = index != -1 && index < beBefore ? index : beBefore;						}					}					int currentIndex = orderedTable.indexOf( table );					if ( beBefore < beAfter ||							( currentIndex != -1 && ( currentIndex < beAfter || currentIndex > beBefore ) )							) {						StringBuilder sb = new StringBuilder(								"Foreign key circularity dependency involving the following tables: "						);						//TODO deduplicate tables						sb.append( table );						if ( beAfter > -1 ) sb.append( ", " ).append( dependentTable );						if ( beBefore < orderedFkSecondPasses.size() ) {							sb.append( ", " ).append( orderedTable.get( beBefore ) );						}						throw new AnnotationException( sb.toString() );					}					currentIndex = currentIndex == -1 ? beBefore : currentIndex;					orderedTable.add( currentIndex, table );					orderedFkSecondPasses.add( currentIndex, sp );				}				else {					endOfQueueFkSecondPasses.add( sp );				}			}			it = orderedFkSecondPasses.listIterator();			while ( it.hasNext() ) {				( (SecondPass) it.next() ).doSecondPass( classes );			}			/*			 * If a second pass raises a recoverableException, queue it for next round			 * stop of no pass has to be processed or if the number of pass to processes			 * does not diminish between two rounds.			 * If some failing pass remain, raise the original exception			 */			boolean stopProcess = false;			RuntimeException originalException = null;			while ( ! stopProcess ) {				List failingSecondPasses = new ArrayList();				it = endOfQueueFkSecondPasses.listIterator();				while ( it.hasNext() ) {					final SecondPass pass = (SecondPass) it.next();					try {						pass.doSecondPass( classes );					}					catch (RecoverableException e) {						failingSecondPasses.add( pass );						if (originalException == null) originalException = (RuntimeException) e.getCause();					}				}				stopProcess = failingSecondPasses.size() == 0 || failingSecondPasses.size() == endOfQueueFkSecondPasses.size();				endOfQueueFkSecondPasses = failingSecondPasses;			}			if (endOfQueueFkSecondPasses.size() > 0) {				throw originalException;			}		}	}	private void processArtifactsOfType(String artifact) {		if ( "hbm".equalsIgnoreCase( artifact ) ) {			log.debug( "Process hbm files" );			for (Document document : hbmDocuments) {				super.add( document );			}			hbmDocuments.clear();			hbmEntities.clear();		}		else if ( "class".equalsIgnoreCase( artifact ) ) {			log.debug( "Process annotated classes" );			//bind classes in the correct order calculating some inheritance state			List<XClass> orderedClasses = orderAndFillHierarchy( annotatedClasses );			Map<XClass, InheritanceState> inheritanceStatePerClass = AnnotationBinder.buildInheritanceStates(					orderedClasses, reflectionManager			);			ExtendedMappings mappings = createExtendedMappings();			for (XClass clazz : orderedClasses) {				//todo use the same extended mapping				AnnotationBinder.bindClass( clazz, inheritanceStatePerClass, mappings );			}			annotatedClasses.clear();			annotatedClassEntities.clear();		}		else {			log.warn( "Unknown artifact: " + artifact );		}	}	private void removeConflictedArtifact(String artifact) {		if ( "hbm".equalsIgnoreCase( artifact ) ) {			for (String entity : hbmEntities.keySet()) {				if ( annotatedClassEntities.containsKey( entity ) ) {					annotatedClasses.remove( annotatedClassEntities.get( entity ) );					annotatedClassEntities.remove( entity );				}			}		}		else if ( "class".equalsIgnoreCase( artifact ) ) {			for (String entity : annotatedClassEntities.keySet()) {				if ( hbmEntities.containsKey( entity ) ) {					hbmDocuments.remove( hbmEntities.get( entity ) );					hbmEntities.remove( entity );				}			}		}	}	private void buildUniqueKeyFromColumnNames(String[] columnNames, Table table, String keyName) {		UniqueKey uc;		int size = columnNames.length;		Column[] columns = new Column[size];		Set<Column> unbound = new HashSet<Column>();		Set<Column> unboundNoLogical = new HashSet<Column>();		ExtendedMappings mappings = createExtendedMappings();		for (int index = 0; index < size; index++) {			String columnName;			try {				columnName = mappings.getPhysicalColumnName( columnNames[index], table );				columns[index] = new Column( columnName );				unbound.add( columns[index] );				//column equals and hashcode is based on column name			}			catch (MappingException e) {				unboundNoLogical.add( new Column( columnNames[index] ) );			}		}		for (Column column : columns) {			if ( table.containsColumn( column ) ) {				uc = table.getOrCreateUniqueKey( keyName );				uc.addColumn( table.getColumn( column ) );				unbound.remove( column );			}		}		if ( unbound.size() > 0 || unboundNoLogical.size() > 0 ) {			StringBuilder sb = new StringBuilder( "Unable to create unique key constraint (" );			for (String columnName : columnNames) {				sb.append( columnName ).append( ", " );			}			sb.setLength( sb.length() - 2 );			sb.append( ") on table " ).append( table.getName() ).append( ": " );			for (Column column : unbound) {				sb.append( column.getName() ).append( ", " );			}			for (Column column : unboundNoLogical) {				sb.append( column.getName() ).append( ", " );			}			sb.setLength( sb.length() - 2 );			sb.append( " not found" );			throw new AnnotationException( sb.toString() );		}	}	@Override	protected void parseMappingElement(Element subelement, String name) {		Attribute rsrc = subelement.attribute( "resource" );		Attribute file = subelement.attribute( "file" );		Attribute jar = subelement.attribute( "jar" );		Attribute pckg = subelement.attribute( "package" );		Attribute clazz = subelement.attribute( "class" );		if ( rsrc != null ) {			log.debug( name + "<-" + rsrc );			addResource( rsrc.getValue() );		}		else if ( jar != null ) {			log.debug( name + "<-" + jar );			addJar( new File( jar.getValue() ) );		}		else if ( file != null ) {			log.debug( name + "<-" + file );			addFile( file.getValue() );		}		else if ( pckg != null ) {			log.debug( name + "<-" + pckg );			addPackage( pckg.getValue() );		}		else if ( clazz != null ) {			log.debug( name + "<-" + clazz );			Class loadedClass = null;			try {				loadedClass = ReflectHelper.classForName( clazz.getValue() );			}			catch (ClassNotFoundException cnf) {				throw new MappingException(						"Unable to load class declared as <mapping class=\"" + clazz.getValue() + "\"/> in the configuration:",						cnf				);			}			catch (NoClassDefFoundError ncdf) {				throw new MappingException(						"Unable to load class declared as <mapping class=\"" + clazz.getValue() + "\"/> in the configuration:",						ncdf				);			}			addAnnotatedClass( loadedClass );		}		else {			throw new MappingException( "<mapping> element in configuration specifies no attributes" );		}	}	@Override	protected void add(org.dom4j.Document doc) throws MappingException {		boolean ejb3Xml = "entity-mappings".equals( doc.getRootElement().getName() );		if ( inSecondPass ) {			//if in second pass bypass the queueing, getExtendedQueue reuse this method			if ( !ejb3Xml ) super.add( doc );		}		else {			if ( !ejb3Xml ) {				final Element hmNode = doc.getRootElement();				Attribute packNode = hmNode.attribute( "package" );				String defaultPackage = packNode != null						? packNode.getValue()						: "";				Set<String> entityNames = new HashSet<String>();				findClassNames( defaultPackage, hmNode, entityNames );				for (String entity : entityNames) {					hbmEntities.put( entity, doc );				}				hbmDocuments.add( doc );			}			else {				List<String> classnames = ( (EJB3ReflectionManager) reflectionManager ).getXMLContext().addDocument( doc );				for (String classname : classnames) {					try {						annotatedClasses.add( reflectionManager.classForName( classname, this.getClass() ) );					}					catch (ClassNotFoundException e) {						throw new AnnotationException( "Unable to load class defined in XML: " + classname, e );					}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?