大家知道通过hibernate cfg或和spring集成的配置里,可用packagesToScan或mapping*之类声明实体类;但有需求可能要在某个项目中编码式加载实体类(例如某个不常用的或特定用户的实体类,并未事先配置),然后进行增删改查操作。下面代码配合spring test framework做了测试(注:hibernate升级到了4.3.final,与4.2有不同,spring3或4测试通过):
@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(locations={"/spring-hibernate.xml"})publicclassConfigurationTestextendsAbstractJUnit4SpringContextTests{publicstaticfinalStringsession_factory="sessionFactory";// 值得注意: org.springframework.beans.factory.FactoryBean that creates a Hibernate org.hibernate.SessionFactorypublicstaticfinalStringlocal_session_factory="&sessionFactory";@TestpublicvoidsessionFactoryAndFactoryBean()throwsClassNotFoundException{SessionFactorysessionFactory=(SessionFactory)applicationContext.getBean(session_factory);Map<String,ClassMetadata>meta=sessionFactory.getAllClassMetadata();for(Entry<String,ClassMetadata>each:meta.entrySet()){ClassMetadatavalue=each.getValue();System.out.println("entity name:"+value.getEntityName());}LocalSessionFactoryBeansessionFactoryBean=(LocalSessionFactoryBean)applicationContext.getBean(local_session_factory);Configurationconfig=sessionFactoryBean.getConfiguration();config.addAnnotatedClass(User.class);ServiceRegistryserviceRegistry=newStandardServiceRegistryBuilder().applySettings(config.getProperties()).build();SessionFactorynewSessionFactory=config.buildSessionFactory(serviceRegistry);Sessionsession=newSessionFactory.openSession();Useruser=newUser();user.setName("username");session.save(user);session.flush();user=(User)session.get(User.class,user.getId());session.close();System.out.println("------"+user.getId());System.out.println("------"+user.getName());Iterator<Table>mappings=config.getTableMappings();while(mappings.hasNext()){Tableeach=mappings.next();System.out.println("table name:"+each.getName());}}}