日期:2014-05-16 浏览次数:20475 次
这几天翻看Hibernate源码,发现Hibernate实现懒加载并不强制要求被加载对象与宿主对象必须在同一个事务中,只要有一个可用的Session,并且在这个Session的上下文(其实就是Session的一级缓存)中注册相应的持久类信息即可,而这个Session是否与被加载对象的宿主处在同一个事务中,Hibernate并不关心,基于此准备实现一个跨事务的懒加载机制来简化复杂业务下的大数据加载问题。
protected Object initialize(final Object proxy) {
if (proxy instanceof HibernateProxy)
return initializeHibernateProxy((HibernateProxy) proxy);
else if (proxy instanceof PersistentCollection)
return initializePersistentCollection((PersistentCollection) proxy);
return proxy;
}
private Object initializePersistentCollection(final PersistentCollection persistentCollection) {
if (persistentCollection.getRole() != null && !persistentCollection.wasInitialized() && ((AbstractPersistentCollection) persistentCollection).getSession() == null) {
return getHibernateTemplate().execute(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException, SQLException {
final SessionImplementor sessionImplementor = (SessionImplementor) session;
final CollectionPersister collectionPersister = sessionImplementor.getFactory().getCollectionPersister(persistentCollection.getRole());
sessionImplementor.getPersistenceContext().addUninitializedDetachedCollection(collectionPersister, persistentCollection);
persistentCollection.setCurrentSession(sessionImplementor);
persistentCollection.forceInitialization();
sessionImplementor.getPersistenceContext().clear();
persistentCollection.unsetSession(sessionImplementor);
return persistentCollection;
}
});
}
return persistentCollection;
}
private Object initializeHibernateProxy(final HibernateProxy proxy) {
final LazyInitializer lazyInitializer = proxy.getHibernateLazyInitializer();
if (lazyInitializer.isUninitialized() && lazyInitializer.getSession() == null) {
return getHibernateTemplate().execute(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException, SQLException {
lazyInitializer.setSession((SessionImplementor) session);
lazyInitializer.initialize();
lazyInitializer.unsetSession();
return proxy;
}
});
}
return proxy;
}public ComponentTypeBean getComponentTypeBean() {
return (ComponentTypeBean) initialize(componentTypeBean);
}
@SuppressWarnings("unchecked")
public Set<PageComponentBean> getPageComponentBeans() {
return (Set<PageComponentBean>) initialize(pageComponentBeans);
} 至此,基于跨事务的懒加载已经实现