tmpEntityToCollectionRoleMap.put( entityName, roles );
}
roles.add( persister.getRole() );
}
}
//加入新的
collectionPersisters.putAll(tempCollectionPersisters);
Iterator itr = tmpEntityToCollectionRoleMap.entrySet().iterator();
while ( itr.hasNext() ) {
final Map.Entry entry = ( Map.Entry ) itr.next();
entry.setValue( Collections.unmodifiableSet( ( Set ) entry.getValue() ) );
}
collectionRolesByEntityParticipant.putAll( tmpEntityToCollectionRoleMap);
// after *all* persisters and named queries are registered
Iterator iter = tmpEntityPersisters.values().iterator();
while ( iter.hasNext() ) {
( (EntityPersister) iter.next() ).postInstantiate();
}
iter = tempCollectionPersisters.values().iterator();
while ( iter.hasNext() ) {
( (CollectionPersister) iter.next() ).postInstantiate();
}
queryPlanCache=new QueryPlanCache(this);
}
我们动态加入实体,动态可进行查询,Hibernate提供几种实体的查询策略,其中一个是我们常用的pojo,若采用该方法,我们得加上hbm与 class类或仅是含注解的class至hibernate的SessionFactory,这种方案并且没有问题,但会遇到当我们修改表单字段,重新生 成对应的实体时,我们就会遇到原有的实体class不能在ClassLoader里卸载。使用的还是旧的Class,达不到动态查询的效果。若使用动态的 ClassLoader,代码将变得很复杂。(尝试过,代码相对比较繁杂)
还好Hibernate提供了另一种实体查询策略,基于Map的动态实体。基于这种方式,我们配置一个一对多的表,其示例代码如下:
MainEntity.hbm.xml
Java代码
< xml version="1.0" >
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
lazy="false"
inverse="true"
cascade="save-update,delete-orphan"
>
SubEntity.hbm.xml
Java代码
< xml version="1.0" >
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
为两实体插入数据后,可动态测试如下:
Java代码
public static void main(String[]args){
ClassPathXmlApplicationContext ctx=new ClassPathXmlApplicationContext("classpath:app-context.xml");
MyAnnotationSessionFactoryBean sessionFactoryBean=(MyAnnotationSessionFactoryBean)ctx.getBean("&sessionFactory");
SessionFactoryImpl sessionFactoryImpl=(SessionFactoryImpl)sessionFactoryBean.getObject();
Configuration cfg=new Configuration();
//cfg.configure();
cfg.addFile("D:/download/eclipse/workspace2/SpringHibernate/src/com/hotent/entity/MainEntity.hbm.xml");
cfg.addFile("D:/download/eclipse/workspace2/SpringHibernate/src/com/hotent/entity/SubEntity.hbm.xml");
cfg.doComplie();
sessionFactoryImpl.addNewConfig(cfg);
MainEntityDao dao=(MainEntityDao)ctx.getBean("mainEntityDao");
List list=dao.query();
for(int i=0;i
Iterator it=map.keySet().iterator();