Create session factory in Hibernate 4

前端 未结 8 2228
猫巷女王i
猫巷女王i 2020-11-30 19:13

I\'m having trouble generating a session factory in Hibernate 4. In Hibernate 3 I simple did:

org.hibernate.cfg.Configuration conf= HibernateUtil
    .getLim         


        
相关标签:
8条回答
  • 2020-11-30 20:06

    The following expresses the experience I had with hibernate 4.0.0.Final.

    The javadoc (distributed under LGPL license) of org.hibernate.cfg.Configuration class states that:

    NOTE : This will be replaced by use of ServiceRegistryBuilder and org.hibernate.metamodel.MetadataSources instead after the 4.0 release at which point this class will become deprecated and scheduled for removal in 5.0. See HHH-6183, HHH-2578 and HHH-6586 for details

    After looking at issue 2578, i used something like this:

    ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().configure().buildServiceRegistry();
    MetadataSources metadataSources = new MetadataSources(serviceRegistry);
    metadataSources.addResource("some_mapping.hbm.xml")
    SessionFactory sessionFactory = metadataSources.buildMetadata().buildSessionFactory();
    

    For it to start reading configuration, i had to modify my hibernate 3.2.6 configuration and mapping files to use xmlns="http://www.hibernate.org/xsd/hibernate-configuration" and xmlns="http://www.hibernate.org/xsd/hibernate-mapping" and also remove the dtd specifications.

    I couldn't find a way for it to inspect mappings defined in hibernate.cfg.xml and hibernate. prefix for hibernate-related properties in hibernate.cfg.xml is no longer optional.

    This might work for some.

    I, for one, ran into some error because mapping files contained <cache usage="read-write" /> and ended up using deprecated Configuration way:

    Configuration configuration = new Configuration().configure();
    SessionFactoryImpl sessionFactory = (SessionFactoryImpl) configuration.buildSessionFactory();
    EventListenerRegistry listenerRegistry = sessionFactory.getServiceRegistry().getService(EventListenerRegistry.class);
    SolrIndexEventListener indexListener = new SolrIndexEventListener(); // a SaveOrUpdateEventListener i wanted to attach
    listenerRegistry.appendListeners(EventType.SAVE_UPDATE, indexListener);
    

    I had to programatically append event listeners because Configuration no longer looks for them in hibernate.cfg.xml

    0 讨论(0)
  • 2020-11-30 20:09
    Configuration hibConfiguration = new Configuration()
                .addResource("wp4core/hibernate/config/table.hbm.xml")
                .configure();       
    
    serviceRegistry = new ServiceRegistryBuilder()
                .applySettings(hibConfiguration.getProperties())
                .buildServiceRegistry();
    
    sessionFactory = hibConfiguration.buildSessionFactory(serviceRegistry);
    session = sessionFactory.withOptions().openSession();
    
    0 讨论(0)
提交回复
热议问题