简体   繁体   English

在Hibernate 4中创建会话工厂

[英]Create session factory in Hibernate 4

I'm having trouble generating a session factory in Hibernate 4. In Hibernate 3 I simple did: 我在Hibernate 4中生成会话工厂时遇到了麻烦。在Hibernate 3中我简单地做了:

org.hibernate.cfg.Configuration conf= HibernateUtil
    .getLimsInitializedConfiguration(systemConfiguration
.getHibernateconfFile());

SessionFactory sf = conf.configure().buildSessionFactory();

Now I need to pass a ServiceRegistry class to buildSessionFactory, but the Javadocs are extremely vague on how to go about this. 现在我需要将ServiceRegistry类传递给buildSessionFactory,但是Javadocs对于如何解决这个问题非常模糊。 Any tips? 有小费吗?

Yes, they have deprecated the previous buildSessionFactory API, and it's quite easy to do well.. you can do something like this.. 是的,他们已经弃用了之前的buildSessionFactory API,并且很容易做得很好..你可以做这样的事情..

EDIT : ServiceRegistryBuilder is deprecated. 编辑 :ServiceRegistryBuilder已弃用。 you must use StandardServiceRegistryBuilder 您必须使用StandardServiceRegistryBuilder

public void testConnection() throws Exception {

            logger.info("Trying to create a test connection with the database.");
            Configuration configuration = new Configuration();
            configuration.configure("hibernate_sp.cfg.xml");
            StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
            SessionFactory sessionFactory = configuration.buildSessionFactory(ssrb.build());
            Session session = sessionFactory.openSession();
            logger.info("Test connection with the database created successfuly.");
    }

For more reference and in depth detail, you can check the hibernate's official test case at https://github.com/hibernate/hibernate-orm/blob/master/hibernate-testing/src/main/java/org/hibernate/testing/junit4/BaseCoreFunctionalTestCase.java function (buildSessionFactory()). 有关更多参考和深入细节,您可以访问https://github.com/hibernate/hibernate-orm/blob/master/hibernate-testing/src/main/java/org/hibernate/testing查看hibernate的官方测试用例。 /junit4/BaseCoreFunctionalTestCase.java函数(buildSessionFactory())。

Try this! 试试这个!

package your.package;

import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateUtil
{
    private static SessionFactory sessionFactory;
    private static ServiceRegistry serviceRegistry;

    static
    {
        try
        {
//          Configuration configuration = new Configuration();
            Configuration configuration = new Configuration().configure();

            serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
            sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        }
        catch (HibernateException he)
        {
            System.err.println("Error creating Session: " + he);
            throw new ExceptionInInitializerError(he);
        }
    }

    public static SessionFactory getSessionFactory()
    {
        return sessionFactory;
    } 
}
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();

The following expresses the experience I had with hibernate 4.0.0.Final. 以下表示我使用hibernate 4.0.0.Final的经验。

The javadoc (distributed under LGPL license) of org.hibernate.cfg.Configuration class states that: org.hibernate.cfg.Configuration类的javadoc(在LGPL许可下分发)声明:

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. 注意:在4.0版本之后,将替换为使用ServiceRegistryBuilderorg.hibernate.metamodel.MetadataSources ,此时此类将被弃用并计划在5.0中删除。 See HHH-6183 , HHH-2578 and HHH-6586 for details 有关详细信息,请参见HHH-6183HHH-2578HHH-6586

After looking at issue 2578, i used something like this: 在查看问题2578后,我使用了这样的东西:

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. 为了开始阅读配置,我不得不修改我的hibernate 3.2.6配置和映射文件以使用xmlns="http://www.hibernate.org/xsd/hibernate-configuration"xmlns="http://www.hibernate.org/xsd/hibernate-mapping"并删除dtd规范。

I couldn't find a way for it to inspect mappings defined in hibernate.cfg.xml and hibernate. 我找不到一种方法来检查hibernate.cfg.xml和hibernate中定义的映射 prefix for hibernate-related properties in hibernate.cfg.xml is no longer optional. 前缀在hibernate.cfg.xml Hibernate相关性不再是可有可无的。

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: 我为一个人遇到了一些错误,因为映射文件包含<cache usage="read-write" />并最终使用不推荐的配置方式:

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 我不得不以编程方式附加事件侦听器,因为Configuration不再在hibernate.cfg.xml中查找它们

Even there is an update in 4.3.0 API. 即使4.3.0 API中有更新。 ServiceRegistryBuilder is also deprecated in 4.3.0 and replaced with the StandardServiceRegistryBuilder. ServiceRegistryBuilder在4.3.0中也已弃用,并替换为StandardServiceRegistryBuilder。 Now the actual code for creating the session factory would look this example on creating session factory . 现在,创建会话工厂的实际代码将在创建会话工厂时查看此示例

[quote from http://www.javabeat.net/session-factory-hibernate-4/] [引自http://www.javabeat.net/session-factory-hibernate-4/]

There are many APIs deprecated in the hibernate core framework. hibernate核心框架中不推荐使用许多API。 One of the frustrating point at this time is, hibernate official documentation is not providing the clear instructions on how to use the new API and it stats that the documentation is in complete. 目前令人沮丧的一点是,hibernate官方文档没有提供关于如何使用新API的明确说明以及文档完整的统计信息。 Also each incremental version gets changes on some of the important API. 此外,每个增量版本都会对某些重要的API进行更改。 One such thing is the new API for creating the session factory in Hibernate 4.3.0 on wards. 其中一个问题是用于在病房中的Hibernate 4.3.0中创建会话工厂的新API。 In our earlier versions we have created the session factory as below: 在我们的早期版本中,我们创建了会话工厂,如下所示:

SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();

The method buildSessionFactory is deprecated from the hibernate 4 release and it is replaced with the new API. 方法buildSessionFactory在hibernate 4发行版中已弃用 ,它将替换为新的API。 If you are using the hibernate 4.3.0 and above, your code has to be: 如果您使用的是hibernate 4.3.0及更高版本,则代码必须是:

Configuration configuration = new Configuration().configure();

StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());

SessionFactory factory = configuration.buildSessionFactory(builder.build());

Class ServiceRegistryBuilder is replaced by StandardServiceRegistryBuilder from 4.3.0. 类ServiceRegistryBuilder由4.3.0中的StandardServiceRegistryBuilder取代。 It looks like there will be lot of changes in the 5.0 release. 看起来5.0版本中会有很多变化。 Still there is not much clarity on the deprecated APIs and the suitable alternatives to use. 对于已弃用的API以及使用的合适替代方案,仍然没有太多的清晰度。 Every incremental release comes up with more deprecated API, they are in way of fine tuning the core framework for the release 5.0. 每个增量版本都会提供更多已弃用的API,它们正在对5.0版本的核心框架进行微调。

In earlier versions session factory was created as below: 在早期版本中,会话工厂创建如下:

SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();

The method buildSessionFactory is deprecated from the hibernate 4 release and it is replaced with the new API. 方法buildSessionFactory在hibernate 4发行版中已弃用,它将替换为新的API。 If you are using the hibernate 4.3.0 and above, your code has to be like: 如果您使用的是hibernate 4.3.0及更高版本,则代码必须如下:

Configuration configuration = new Configuration().configure();
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().
applySettings(configuration.getProperties());
SessionFactory factory = configuration.buildSessionFactory(builder.build());

The method buildSessionFactory is deprecated from the Hibernate 4 release and it is replaced with the new API. 方法buildSessionFactory在Hibernate 4版本中已弃用,它将替换为新的API。 If you are using the Hibernate 4.3.0 and above, your code has to be: 如果您使用的是Hibernate 4.3.0及更高版本,则您的代码必须是:

Configuration configuration = new Configuration().configure();

StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
        .applySettings(configuration.getProperties());

SessionFactory factory = configuration.buildSessionFactory(builder.build());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM