⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 hbmbinder.java

📁 hibernate-3.1.3-all-src.zip 面向对象的访问数据库工具
💻 JAVA
📖 第 1 页 / 共 5 页
字号:
// $Id: HbmBinder.java 9157 2006-01-27 18:49:01Z maxcsaucdk $
package org.hibernate.cfg;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Properties;
import java.util.StringTokenizer;

import org.apache.commons.collections.SequencedHashMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.hibernate.CacheMode;
import org.hibernate.EntityMode;
import org.hibernate.FetchMode;
import org.hibernate.FlushMode;
import org.hibernate.MappingException;
import org.hibernate.engine.FilterDefinition;
import org.hibernate.engine.NamedQueryDefinition;
import org.hibernate.engine.Versioning;
import org.hibernate.id.PersistentIdentifierGenerator;
import org.hibernate.mapping.Any;
import org.hibernate.mapping.Array;
import org.hibernate.mapping.AuxiliaryDatabaseObject;
import org.hibernate.mapping.Backref;
import org.hibernate.mapping.Bag;
import org.hibernate.mapping.Collection;
import org.hibernate.mapping.Column;
import org.hibernate.mapping.Component;
import org.hibernate.mapping.DependantValue;
import org.hibernate.mapping.Fetchable;
import org.hibernate.mapping.Filterable;
import org.hibernate.mapping.Formula;
import org.hibernate.mapping.IdentifierBag;
import org.hibernate.mapping.IdentifierCollection;
import org.hibernate.mapping.IndexBackref;
import org.hibernate.mapping.IndexedCollection;
import org.hibernate.mapping.Join;
import org.hibernate.mapping.JoinedSubclass;
import org.hibernate.mapping.KeyValue;
import org.hibernate.mapping.List;
import org.hibernate.mapping.ManyToOne;
import org.hibernate.mapping.Map;
import org.hibernate.mapping.MetaAttribute;
import org.hibernate.mapping.OneToMany;
import org.hibernate.mapping.OneToOne;
import org.hibernate.mapping.PersistentClass;
import org.hibernate.mapping.PrimitiveArray;
import org.hibernate.mapping.Property;
import org.hibernate.mapping.PropertyGeneration;
import org.hibernate.mapping.RootClass;
import org.hibernate.mapping.Selectable;
import org.hibernate.mapping.Set;
import org.hibernate.mapping.SimpleAuxiliaryDatabaseObject;
import org.hibernate.mapping.SimpleValue;
import org.hibernate.mapping.SingleTableSubclass;
import org.hibernate.mapping.Subclass;
import org.hibernate.mapping.Table;
import org.hibernate.mapping.ToOne;
import org.hibernate.mapping.TypeDef;
import org.hibernate.mapping.UnionSubclass;
import org.hibernate.mapping.UniqueKey;
import org.hibernate.mapping.Value;
import org.hibernate.persister.entity.JoinedSubclassEntityPersister;
import org.hibernate.persister.entity.SingleTableEntityPersister;
import org.hibernate.persister.entity.UnionSubclassEntityPersister;
import org.hibernate.type.DiscriminatorType;
import org.hibernate.type.ForeignKeyDirection;
import org.hibernate.type.Type;
import org.hibernate.type.TypeFactory;
import org.hibernate.util.JoinedIterator;
import org.hibernate.util.ReflectHelper;
import org.hibernate.util.StringHelper;

/**
 * Walks an XML mapping document and produces the Hibernate configuration-time metamodel (the
 * classes in the <tt>mapping</tt> package)
 *
 * @author Gavin King
 */
public final class HbmBinder {

	private static final Log log = LogFactory.getLog( HbmBinder.class );

	/**
	 * Private constructor to disallow instantiation.
	 */
	private HbmBinder() {
	}

	/**
	 * The main contract into the hbm.xml-based binder. Performs necessary binding operations
	 * represented by the given DOM.
	 *
	 * @param doc The DOM to be parsed and bound.
	 * @param mappings Current bind state.
	 * @param inheritedMetas Any inherited meta-tag information.
	 * @throws MappingException
	 */
	public static void bindRoot(Document doc, Mappings mappings, java.util.Map inheritedMetas)
			throws MappingException {

		java.util.List names = HbmBinder.getExtendsNeeded( doc, mappings );
		if ( !names.isEmpty() ) {
			// classes mentioned in extends not available - so put it in queue
			Element hmNode = doc.getRootElement();
			Attribute packNode = hmNode.attribute( "package" );
			String packageName = null;
			if ( packNode != null ) {
				packageName = packNode.getValue();
			}
			Iterator itr = names.iterator();
			while ( itr.hasNext() ) {
				String extendsName = (String) itr.next();
				mappings.addToExtendsQueue( new ExtendsQueueEntry( extendsName, packageName, doc ) );
			}
			return;
		}

		Element hmNode = doc.getRootElement();
		inheritedMetas = getMetas( hmNode, inheritedMetas, true ); // get meta's from
																	// <hibernate-mapping>
		extractRootAttributes( hmNode, mappings );

		Iterator filterDefs = hmNode.elementIterator( "filter-def" );
		while ( filterDefs.hasNext() ) {
			parseFilterDef( (Element) filterDefs.next(), mappings );
		}

		Iterator typeDefs = hmNode.elementIterator( "typedef" );
		while ( typeDefs.hasNext() ) {
			Element typeDef = (Element) typeDefs.next();
			String typeClass = typeDef.attributeValue( "class" );
			String typeName = typeDef.attributeValue( "name" );
			Iterator paramIter = typeDef.elementIterator( "param" );
			Properties parameters = new Properties();
			while ( paramIter.hasNext() ) {
				Element param = (Element) paramIter.next();
				parameters.setProperty( param.attributeValue( "name" ), param.getTextTrim() );
			}

			mappings.addTypeDef( typeName, typeClass, parameters );
		}

		Iterator nodes = hmNode.elementIterator( "class" );
		while ( nodes.hasNext() ) {
			Element n = (Element) nodes.next();
			RootClass rootclass = new RootClass();
			bindRootClass( n, rootclass, mappings, inheritedMetas );
			mappings.addClass( rootclass );
		}

		Iterator subclassnodes = hmNode.elementIterator( "subclass" );
		while ( subclassnodes.hasNext() ) {
			Element subnode = (Element) subclassnodes.next();
			PersistentClass superModel = getSuperclass( mappings, subnode );
			handleSubclass( superModel, mappings, subnode, inheritedMetas );
		}

		Iterator joinedsubclassnodes = hmNode.elementIterator( "joined-subclass" );
		while ( joinedsubclassnodes.hasNext() ) {
			Element subnode = (Element) joinedsubclassnodes.next();
			PersistentClass superModel = getSuperclass( mappings, subnode );
			handleJoinedSubclass( superModel, mappings, subnode, inheritedMetas );
		}

		Iterator unionsubclassnodes = hmNode.elementIterator( "union-subclass" );
		while ( unionsubclassnodes.hasNext() ) {
			Element subnode = (Element) unionsubclassnodes.next();
			PersistentClass superModel = getSuperclass( mappings, subnode );
			handleUnionSubclass( superModel, mappings, subnode, inheritedMetas );
		}

		nodes = hmNode.elementIterator( "query" );
		while ( nodes.hasNext() ) {
			bindNamedQuery( (Element) nodes.next(), null, mappings );
		}

		nodes = hmNode.elementIterator( "sql-query" );
		while ( nodes.hasNext() ) {
			bindNamedSQLQuery( (Element) nodes.next(), null, mappings );
		}

		nodes = hmNode.elementIterator( "resultset" );
		while ( nodes.hasNext() ) {
			bindResultSetMappingDefinition( (Element) nodes.next(), null, mappings );
		}

		nodes = hmNode.elementIterator( "import" );
		while ( nodes.hasNext() ) {
			Element n = (Element) nodes.next();
			String className = getClassName( n.attribute( "class" ), mappings );
			Attribute renameNode = n.attribute( "rename" );
			String rename = ( renameNode == null ) ?
					StringHelper.unqualify( className ) :
					renameNode.getValue();
			log.debug( "Import: " + rename + " -> " + className );
			mappings.addImport( className, rename );
		}

		nodes = hmNode.elementIterator( "database-object");
		while ( nodes.hasNext() ) {
			Element auxDbObjectNode = ( Element ) nodes.next();
			AuxiliaryDatabaseObject auxDbObject = null;
			Element definitionNode = auxDbObjectNode.element( "definition" );
			if ( definitionNode != null ) {
				try {
					auxDbObject = ( AuxiliaryDatabaseObject ) ReflectHelper
					        .classForName( definitionNode.attributeValue( "class" ) )
					        .newInstance();
				}
				catch( ClassNotFoundException e ) {
					throw new MappingException(
					        "could not locate custom database object class [" +
					        definitionNode.attributeValue( "class" ) + "]"
						);
				}
				catch( Throwable t ) {
					throw new MappingException(
					        "could not instantiate custom database object class [" +
					        definitionNode.attributeValue( "class" ) + "]"
						);
				}
			}
			else {
				auxDbObject = new SimpleAuxiliaryDatabaseObject(
				        auxDbObjectNode.elementTextTrim( "create" ),
				        auxDbObjectNode.elementTextTrim( "drop" )
					);
			}

			Iterator dialectScopings = auxDbObjectNode.elementIterator( "dialect-scope" );
			while ( dialectScopings.hasNext() ) {
				Element dialectScoping = ( Element ) dialectScopings.next();
				auxDbObject.addDialectScope( dialectScoping.attributeValue( "name" ) );
			}

			mappings.addAuxiliaryDatabaseObject( auxDbObject );
		}
	}

	private static void extractRootAttributes(Element hmNode, Mappings mappings) {
		Attribute schemaNode = hmNode.attribute( "schema" );
		mappings.setSchemaName( ( schemaNode == null ) ? null : schemaNode.getValue() );

		Attribute catalogNode = hmNode.attribute( "catalog" );
		mappings.setCatalogName( ( catalogNode == null ) ? null : catalogNode.getValue() );

		Attribute dcNode = hmNode.attribute( "default-cascade" );
		mappings.setDefaultCascade( ( dcNode == null ) ? "none" : dcNode.getValue() );

		Attribute daNode = hmNode.attribute( "default-access" );
		mappings.setDefaultAccess( ( daNode == null ) ? "property" : daNode.getValue() );

		Attribute dlNode = hmNode.attribute( "default-lazy" );
		mappings.setDefaultLazy( dlNode == null || dlNode.getValue().equals( "true" ) );

		Attribute aiNode = hmNode.attribute( "auto-import" );
		mappings.setAutoImport( ( aiNode == null ) ? true : "true".equals( aiNode.getValue() ) );

		Attribute packNode = hmNode.attribute( "package" );
		if ( packNode != null ) mappings.setDefaultPackage( packNode.getValue() );
	}

	/**
	 * Responsible for perfoming the bind operation related to an &lt;class/&gt; mapping element.
	 *
	 * @param node The DOM Element for the &lt;class/&gt; element.
	 * @param rootClass The mapping instance to which to bind the information.
	 * @param mappings The current bind state.
	 * @param inheritedMetas Any inherited meta-tag information.
	 * @throws MappingException
	 */
	public static void bindRootClass(Element node, RootClass rootClass, Mappings mappings,
			java.util.Map inheritedMetas) throws MappingException {
		bindClass( node, rootClass, mappings, inheritedMetas );
		inheritedMetas = getMetas( node, inheritedMetas, true ); // get meta's from <class>
		bindRootPersistentClassCommonValues( node, inheritedMetas, mappings, rootClass );
	}

	private static void bindRootPersistentClassCommonValues(Element node,
			java.util.Map inheritedMetas, Mappings mappings, RootClass entity)
			throws MappingException {

		// DB-OBJECTNAME

		Attribute schemaNode = node.attribute( "schema" );
		String schema = schemaNode == null ?
				mappings.getSchemaName() : schemaNode.getValue();

		Attribute catalogNode = node.attribute( "catalog" );
		String catalog = catalogNode == null ?
				mappings.getCatalogName() : catalogNode.getValue();

		Table table = mappings.addTable(
				schema,
				catalog,
				getClassTableName( entity, node, schema, catalog, null, mappings ),
				getSubselect( node ),
				entity.isAbstract() == null ? false : entity.isAbstract().booleanValue()
			);
		entity.setTable( table );
		bindComment(table, node);

		log.info(
				"Mapping class: " + entity.getEntityName() +
				" -> " + entity.getTable().getName()
			);

		// MUTABLE
		Attribute mutableNode = node.attribute( "mutable" );
		entity.setMutable( ( mutableNode == null ) || mutableNode.getValue().equals( "true" ) );

		// WHERE
		Attribute whereNode = node.attribute( "where" );
		if ( whereNode != null ) entity.setWhere( whereNode.getValue() );

		// CHECK
		Attribute chNode = node.attribute( "check" );
		if ( chNode != null ) table.addCheckConstraint( chNode.getValue() );

		// POLYMORPHISM
		Attribute polyNode = node.attribute( "polymorphism" );
		entity.setExplicitPolymorphism( ( polyNode != null )
			&& polyNode.getValue().equals( "explicit" ) );

		// ROW ID
		Attribute rowidNode = node.attribute( "rowid" );
		if ( rowidNode != null ) table.setRowId( rowidNode.getValue() );

		Iterator subnodes = node.elementIterator();
		while ( subnodes.hasNext() ) {

			Element subnode = (Element) subnodes.next();
			String name = subnode.getName();

			if ( "id".equals( name ) ) {
				// ID
				bindSimpleId( subnode, entity, mappings, inheritedMetas );
			}
			else if ( "composite-id".equals( name ) ) {
				// COMPOSITE-ID
				bindCompositeId( subnode, entity, mappings, inheritedMetas );
			}
			else if ( "version".equals( name ) || "timestamp".equals( name ) ) {
				// VERSION / TIMESTAMP
				bindVersioningProperty( table, subnode, mappings, name, entity, inheritedMetas );
			}
			else if ( "discriminator".equals( name ) ) {
				// DISCRIMINATOR
				bindDiscriminatorProperty( table, entity, subnode, mappings );
			}
			else if ( "cache".equals( name ) ) {
				entity.setCacheConcurrencyStrategy( subnode.attributeValue( "usage" ) );
				entity.setCacheRegionName( subnode.attributeValue( "region" ) );
				entity.setLazyPropertiesCacheable( !"non-lazy".equals( subnode.attributeValue( "include" ) ) );
			}

		}

⌨️ 快捷键说明

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