开始看Hibernate reference,运行hibernate的test中的代码。
Environment是一个非常重要的类。它定义了很多常量,最重要的是hibernate的入口在这里。在Environemt类中有段static 代码:
static {
//一些常量设置
//导入hibernate.properties到GLOBAL_PROPERTIES
InputStream stream = ConfigHelper.getResourceAsStream("/hibernate.properties");
...
GLOBAL_PROPERTIES.load(stream);
...
stream.close();
...
//将系统属性放入全局属性GLOBAL_PROPERTIES中
try {
GLOBAL_PROPERTIES.putAll( System.getProperties() );
}
catch (SecurityException se) {
log.warn("could not copy system properties, system properties will be ignored");
}
//检查是否有属性废弃了或改名了
verifyProperties(GLOBAL_PROPERTIES);
//其他一些设置。。。
//看db driver/JVM? 是否支持产生key的方法
boolean getGeneratedKeysSupport;
try {
Statement.class.getMethod("getGeneratedKeys", null);
getGeneratedKeysSupport = true;
}
catch (NoSuchMethodException nsme) {
getGeneratedKeysSupport = false;
}
JVM_SUPPORTS_GET_GENERATED_KEYS = getGeneratedKeysSupport;
if (!JVM_SUPPORTS_GET_GENERATED_KEYS) log.info("JVM does not support Statement.getGeneratedKeys()");
//查JDK是否有java.util.LinkedHashSet类
//Timestamp似乎有点问题
JVM_HAS_TIMESTAMP_BUG = new Timestamp(123456789).getTime() != 123456789;
if (JVM_HAS_TIMESTAMP_BUG) log.info("using workaround for JVM bug in java.sql.Timestamp");
Timestamp t = new Timestamp(0);
t.setNanos(5 * 1000000);
JVM_HAS_JDK14_TIMESTAMP = t.getTime() == 5;
if (JVM_HAS_JDK14_TIMESTAMP) {
log.info("using JDK 1.4 java.sql.Timestamp handling");
}
else {
log.info("using pre JDK 1.4 java.sql.Timestamp handling");
}
}
然后正常的一个流程:
Configuration cfg = new Configuration();
//从配置文件中得到的各种属性设置
cfg.setProperty();
//得到所有mapping文件或mapping类
cfg.addResource(//mapping文件名);
或cfg.addClass(//类名)
//针对每个resource,有个HbmBinder来读xml文件,并产生配置时期模型类,就是在org.hibernate.mapping包中的各个类,
如Any,OneToMany,List,Join等。称为配置时期的模型configuration-time metamodel。
cfg.buildMappings(); //这里对复合查询进行,外键等进行处理
SessionFactory sessionFactory = cfg.buildSessionFactory();
{//...
return new SessionFactoryImpl(
this,
mapping,
settings,
getInitializedEventListeners()
);
}
Session s = sessionFactory.openSession(){
//org.hibernate.impl.SessionImpl
return new SessionImpl(
connection,
this,
autoClose,
timestamp,
sessionLocalInterceptor == null ? interceptor : sessionLocalInterceptor,
settings.getDefaultEntityMode(),
settings.isFlushBeforeCompletionEnabled(),
settings.isAutoCloseSessionEnabled(),
settings.getConnectionReleaseMode()
);
}
Transaction tx = s.beginTransaction();
....
tx.commit();
s.close();