Hibernate源码解读——启动

 做为javar的必学框架,我相信Hibernate源码也是被研究过无数次了。不过,别人研究过不表明我就不须要看了。java

 

这里我以个人视野简单的过一遍。各位iteye的朋友有时间能够看看。如何已经很熟悉这个了就不用看了,不然看也是浪费时间。我研究的方法很是简单,就是反复读源码,一遍不行,二遍,或者三遍。。。node

 

从Hibernate源码看它的启动过程:web

 

Hibernate的启动是从Configuration开始的。Configuration既是它的配置中心,也是它的启动最初点。面试

Configuration提供了几个重载的configure方法,用来读取配置,默认,固然就是hibernate.cfg.xml。spring

configure调用doConfigure,返回Configuration。sql

 

doConfigure(org.dom4j.Document doc)很重要:数据库

protected Configuration doConfigure(org.dom4j.Document doc) throws HibernateException {
		//获取session-factory节点sfNode
		Element sfNode = doc.getRootElement().element( "session-factory" );
		String name = sfNode.attributeValue( "name" );
		if ( name != null ) {
			properties.setProperty( Environment.SESSION_FACTORY_NAME, name );
		}
		//处理sfNode的子节点property
		addProperties( sfNode );
		//处理sfNode的其余子节点,主要是mapping、listener、event
		parseSessionFactory( sfNode, name );

		Element secNode = doc.getRootElement().element( "security" );
		if ( secNode != null ) {
			parseSecurity( secNode );//处理doc的其余子节点,security,通常用的少
		}
		return this;
	}

 

 

mapping 是关键,相似下面的配置apache

<mapping resource="com/bjsxt/drp/business/itemmgr/model/DataDict.hbm.xml"/>api

 

protected void parseMappingElement(Element subelement, String name) {
		Attribute rsrc = subelement.attribute( "resource" );
		Attribute file = subelement.attribute( "file" );
		Attribute jar = subelement.attribute( "jar" );
		Attribute pkg = subelement.attribute( "package" );
		Attribute clazz = subelement.attribute( "class" );	
		addResource( rsrc.getValue() );
		addJar( new File( jar.getValue() ) );
                 addFile( file.getValue() );
	}

 

 

经常使用的固然就是addResource,它调用addInputStream,而后是add(org.dom4j.Document doc),而后是HbmBinder.bindRoot( doc, createMappings(), CollectionHelper.EMPTY_MAP );缓存

 

HbmBinder至关重要,他处理了Xxx.hbm.xml的各类配置;

——Walks an XML mapping document and produces the Hibernate configuration-time metamodel (the classes in the mapping)

 

 

 

 

bindRoot首先处理package属性,而后是其下面的各类元素:

filter-def

typedef

class:  经过bindRootClass-bindRootPersistentClassCommonValues处理class下的 property元素等

subclass

typedef

query

sql-query

import

database-object

 

else if ( "class".equals( elementName ) ) {
				RootClass rootclass = new RootClass();
				bindRootClass( element, rootclass, mappings, inheritedMetas );
				mappings.addClass( rootclass );
			}


---->>>
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 );
	}

 

 

继续跟踪,咱们发现,相似 Xxx.hbm.xml的配置,里面的class元素,都被放到了 RootClass 里面:

public class RootClass extends PersistentClass implements TableOwner

它是一个实际对数据进行封装的类,主要是封装了下面的 属性,及对应的setter、getter方法。

private Property identifierProperty; //may be final
	private KeyValue identifier; //may be final
	private Property version; //may be final
	private boolean polymorphic;
	private String cacheConcurrencyStrategy;
	private String cacheRegionName;
	private boolean lazyPropertiesCacheable = true;
	private Value discriminator; //may be final
	private boolean mutable = true;
	private boolean embeddedIdentifier = false; // may be final
	private boolean explicitPolymorphism;
	private Class entityPersisterClass;
	private boolean forceDiscriminator = false;
	private String where;
	private Table table;
	private boolean discriminatorInsertable = true;
	private int nextSubclassId = 0;

 PersistentClass 也是很重要,——Mapping for an entity

 

 

 

bindClass主要对 class里面的属性进行处理;

而bindRootPersistentClassCommonValues是对class下元素进行处理;

 

bindRootPersistentClassCommonValues很重要,二级缓存标签cache 也是在这里进行处理的!

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 && entity.isAbstract().booleanValue()
		);
	entity.setTable( table );
	bindComment(table, node);

	// 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" ) ) );
		}
	}

	// Primary key constraint
	entity.createPrimaryKey();

	createClassProperties( node, entity, mappings, inheritedMetas );
}

 

 

 

这个类,我还没彻底看懂,众所周知,hibernate的配置至关繁多复杂。我就经常记不住,有一次面试的时候,面试官问我hibernate的父类子类继承关系怎么配置,我记不得,因此也说不清。。。 给他留下很差印象。启动,先说到这里。有时间再仔细看看。

 

总之,configure以后,hibernate的配置就生效,可使用了!

 

好比,经过配置获取可以使用的 SessionFactory :

factory = cfg.buildSessionFactory();//  获取 factory 是hibernate 许多框架发挥巨大做用的最基础!

等等。

 

固然,咱们通常不用直接经过,Configuration的静态方法configure来启动hibernate。在web应用中,咱们经过web容器的相关配置来启动。

 

好比,在和struts集成(没有spring)的时候,咱们一般写一个相似HibernateUtil负责从配置文件中获取、关闭SessionFactory :

public class HibernateUtils {

	private static SessionFactory factory;
	
	static {
		try {
			Configuration cfg = new Configuration().configure();
			factory = cfg.buildSessionFactory();
		}catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	public static SessionFactory getSessionFactory() {
		return factory;
	}
	
	public static Session getSession() {
		return factory.openSession();
	}
	
	public static void closeSession(Session session) {
		if (session != null) {
			if (session.isOpen()) {
				session.close();
			}
		}
	}
}

 

 

固然,这其实仍是要

Configuration cfg = new Configuration().configure();
   factory = cfg.buildSessionFactory();

 

但因为他是静态初始化块的,因此配置只会被读取一次。固然,session仍是要每次来获取的:

factory.openSession(),(是否每次打开同一个session根据状况须要)

factory还提供了api来获取不一样的session:

openSession()

openSession(Connection connection)

openSession(Interceptor interceptor)

getCurrentSession()

openStatelessSession()

openStatelessSession(Connection connection)

 

 

另外,咱们能够经过其余方式启动hibernate,插件方式:

import org.apache.struts.action.PlugIn;
import org.apache.struts.action.ActionServlet;
import org.apache.struts.config.ModuleConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletContext;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernatePlugIn implements PlugIn {
	public void destroy() {
	}

	public void init(ActionServlet servlet, ModuleConfig config)
			throws ServletException {
		try {
			ServletContext context = servlet.getServletContext();
			SessionFactory sf = new Configuration().configure()
					.buildSessionFactory();
			context.setAttribute("org.hibernate.SessionFactory", sf);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
}

 而后在struts-config.xml配置插件信息:

 

 <plug-in className="homepage.HibernatePlugIn">    <set-property property="configFilePath"   value="/WEB-INF/classes/hibernate.cfg.xml" />    <set-property property="storeInServletContext" value="true" /> 

</plug-in>
而后利用java.naming.Context,java.naming.InitiaContext来查找
Context ct = new InitialContext();     

sessions=(SessionFactory) ct.lookup("hibernate/session_factory");     

session=sessions.openSession();

而后再封装成相似HibernateUtil的类,而后就能够在action中使用了。

 

 

若是集成在spring中,咱们一般有以下的配置:

 <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
  <property name="configLocation">
   <value>classpath:hibernate.cfg.xml</value>
  </property> 
 </bean>    

从而经过org.springframework.orm.hibernate3.LocalSessionFactoryBean读取hibernate配置,进而在必要的时候使用hibernateapi,能够说,它这个包装是颇有用的。

 

spring提供有用的HibernateDaoSupport类,简化业务中对数据库的交互:

咱们在业务中(一般是dao层)只要继承HibernateDaoSupport,而后再在spring对齐作相应的配置,就能够直接使用HibernateDaoSupport提供的getHibernateTemplate()来获取所需的hibernate session相关方法了,如

save、load、query、update、delete等