Hibernate是否弃用了buildSessionFactory()配置方法


215

当我将Hibernate版本从3.6.8更新到4.0.0时,buildSessionFactory()在此行中收到有关过时方法的警告:

private static final SessionFactory sessionFactory =
         new Configuration().configure().buildSessionFactory();

Javadoc建议使用另一种方法

buildSessionFactory(ServiceRegistry serviceRegistry)

但是在文档中我发现不推荐使用的变体:(

这个小小的误解可以帮助我吗?


即使在4.3.8快速入门指南中,他们也使用以下示例:new Configuration().configure()。buildSessionFactory(); :(
Venkata Raju 2015年

@VenkataRaju可能不错,因为在Hibernate 5中一切都转回去并且此示例正确,但是(!)这里的所有配置示例均不适用于Hibernate 5
v.ladynev '16

Answers:


374

是的,已弃用。将您的SessionFactory替换为以下内容:

Hibernate 4.0、4.1、4.2中

private static SessionFactory sessionFactory;
private static ServiceRegistry serviceRegistry;

public static SessionFactory createSessionFactory() {
    Configuration configuration = new Configuration();
    configuration.configure();
    ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(
            configuration.getProperties()). buildServiceRegistry();
    sessionFactory = configuration.buildSessionFactory(serviceRegistry);
    return sessionFactory;
}

更新:

Hibernate 4.3中,不推荐使用 ServiceRegistryBuilder 。请改用以下内容。

serviceRegistry = new StandardServiceRegistryBuilder().applySettings(
            configuration.getProperties()).build();

6
org.hibernate.service.ServiceRegistryBuilder也被取消了!
Accollat​​ivo 2014年

11
是的,看来似乎不赞成使用ServiceRegistryBuilder,而是查看文档,他们建议改用StandardServiceRegistryBuilder。所以我想现在的调用应该是新的StandardRegistryBuilder()。applySettings(configuration.getProperties())。build();
西蒙B

我在hibernate 4.3中找不到StandardRegistryBuilder,可能是在那里进行了更改吗?
Dejell 2014年

7
而不是build(),需要buildServiceRegistry(),对吗?我找不到ServiceRegistry.build()。
赫伯特

43
休眠团队的任务似乎是弃用他们创建的所有内容。
3urdoch 2014年

16

是的,已弃用。 http://docs.jboss.org/hibernate/core/4.0/javadocs/org/hibernate/cfg/Configuration.html#buildSessionFactory()专门告诉您使用找到的另一种方法(buildSessionFactory(ServiceRegistry serviceRegistry))-因此,请使用它。

该文档在各个发行版之间进行了复制,并且可能尚未更新(它们不会在每个发行版中都重写该手册)-因此请相信Javadocs。

可以在以下位置查看此更改的详细信息:

一些其他参考:


那么,我们现在如何进行会议?分配给serviceRegistry接口的对象是什么?
Ismail Marmoush

@IsmailMarmoush-我还没有玩太多,但是添加了一些其他参考。
ziesemer 2011年

7

要么

public class Hbutil {

    private static SessionFactory sessionFactory;
    private static ServiceRegistry serviceRegistry;

    private static SessionFactory configureSessionFactory() throws HibernateException {
        Configuration configuration = new Configuration();
        configuration.configure();
        serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();        
        sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        return sessionFactory;
    }

    public static SessionFactory getSessionFactory() {
        return configureSessionFactory();

    }
}

此代码中使用了一些不推荐使用的方法。
凯文·鲍尔索克斯

6

验证代码可以在Hibernate 4.3.0中工作。注意,您可以删除XML文件名参数,或者在其中提供您自己的路径。这类似于此处的其他帖子(但错别字已纠正),但这是正确的。

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;    


Configuration configuration = new Configuration();
configuration.configure("/com/rtw/test/hiber/hibernate.cfg.xml");
ServiceRegistry  serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();        
    sessionFactory = configuration.buildSessionFactory(serviceRegistry);


4

从最新的Hibernate版本4.3.0开始,创建SessionFactory对象的更好方法如下:

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

收到错误消息:配置类型中的方法buildSessionFactory()不适用于参数(StandardServiceRegistry)
Anju

4

在不同版本的文档之间发现差异并不罕见。大多数开发人员将文档视为繁琐的工作,并且倾向于推迟文档。

根据经验,如果javadoc说了一件事,而某些非javadoc文档与此相矛盾,则javadoc可能更准确。程序员更有可能通过更改代码来使Javadoc保持最新状态……因为Javadoc的“源”与代码位于同一文件中。

对于@deprecated标签,可以肯定地确定javadoc更准确。开发人员在仔细考虑之后便弃用了这些东西……(通常来说)他们并不会弃用它们。


1
...并且他们不会不赞成他们。...除非被称为System.getenv(String) bugs.sun.com/bugdatabase/view_bug.do?bug_id=4199068
bestsss 2011年

1
经常发现垃圾项目,其懒惰的开发人员不必费心将文档与代码保持一致,从而使用户发疯,而这些项目则试图通过翻炒自己并希望在那里来弄清楚那些血腥垃圾的工作方式。不仅仅是/ ** TODO:
commentment

@bestsss ...或称为Configuration.buildSessionFactory();)
v.ladynev '16

3

如果您使用的是Hibernate 5.2及更高版本,则可以使用以下代码:

  private static StandardServiceRegistry registry;
  private static SessionFactory sessionFactory;

  public static SessionFactory getSessionFactory() {
    if (sessionFactory == null) {
      try {
        // Creating a registry
        registry = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();

        // Create the MetadataSources
        MetadataSources sources = new MetadataSources(registry);

        // Create the Metadata
        Metadata metadata = sources.getMetadataBuilder().build();

        // Create SessionFactory
        sessionFactory = metadata.getSessionFactoryBuilder().build();

      } catch (Exception e) {
        e.printStackTrace();
        if (registry != null) {
          StandardServiceRegistryBuilder.destroy(registry);
        }
      }
    }
    return sessionFactory;
  }

  //To shut down
 public static void shutdown() {
    if (registry != null) {
      StandardServiceRegistryBuilder.destroy(registry);
    }
  }

2

TL; DR

是的。有一些更好的方法来引导Hibernate,如下所示。

休眠本机引导程序

Configuration与使用BootstrapServiceRegistryBuilderHibernate 4之后引入的相比,旧版对象的功能不那么强大:

final BootstrapServiceRegistryBuilder bsrb = new BootstrapServiceRegistryBuilder()
    .enableAutoClose();

Integrator integrator = integrator();
if (integrator != null) {
    bsrb.applyIntegrator( integrator );
}

final BootstrapServiceRegistry bsr = bsrb.build();

final StandardServiceRegistry serviceRegistry = 
    new StandardServiceRegistryBuilder(bsr)
        .applySettings(properties())
        .build();

final MetadataSources metadataSources = new MetadataSources(serviceRegistry);

for (Class annotatedClass : entities()) {
    metadataSources.addAnnotatedClass(annotatedClass);
}

String[] packages = packages();
if (packages != null) {
    for (String annotatedPackage : packages) {
        metadataSources.addPackage(annotatedPackage);
    }
}

String[] resources = resources();
if (resources != null) {
    for (String resource : resources) {
        metadataSources.addResource(resource);
    }
}

final MetadataBuilder metadataBuilder = metadataSources.getMetadataBuilder()
    .enableNewIdentifierGeneratorSupport(true)
    .applyImplicitNamingStrategy(ImplicitNamingStrategyLegacyJpaImpl.INSTANCE);

final List<Type> additionalTypes = additionalTypes();
if (additionalTypes != null) {
    additionalTypes.stream().forEach(type -> {
        metadataBuilder.applyTypes((typeContributions, sr) -> {
            if(type instanceof BasicType) {
                typeContributions.contributeType((BasicType) type);
            } else if (type instanceof UserType ){
                typeContributions.contributeType((UserType) type);
            } else if (type instanceof CompositeUserType) {
                typeContributions.contributeType((CompositeUserType) type);
            }
        });
    });
}

additionalMetadata(metadataBuilder);

MetadataImplementor metadata = (MetadataImplementor) metadataBuilder.build();

final SessionFactoryBuilder sfb = metadata.getSessionFactoryBuilder();
Interceptor interceptor = interceptor();
if(interceptor != null) {
    sfb.applyInterceptor(interceptor);
}

SessionFactory sessionFactory = sfb.build();

JPA引导程序

您还可以使用JPA引导Hibernate:

PersistenceUnitInfo persistenceUnitInfo = persistenceUnitInfo(getClass().getSimpleName());
Map configuration = properties();

Interceptor interceptor = interceptor();
if (interceptor != null) {
    configuration.put(AvailableSettings.INTERCEPTOR, interceptor);
}

Integrator integrator = integrator();
if (integrator != null) {
    configuration.put(
        "hibernate.integrator_provider", 
        (IntegratorProvider) () -> Collections.singletonList(integrator));
}

EntityManagerFactoryBuilderImpl entityManagerFactoryBuilder = 
    new EntityManagerFactoryBuilderImpl(
        new PersistenceUnitInfoDescriptor(persistenceUnitInfo), 
        configuration
);
EntityManagerFactory entityManagerFactory = entityManagerFactoryBuilder.build();

这样,您将构建EntityManagerFactory而不是SessionFactory。但是,也SessionFactory扩展了EntityManagerFactory, so the actual object that's built is aSessionFactoryImpl`。

结论

这两种引导方法会影响休眠行为。使用本机引导程序时,Hibernate会以旧模式运行,该模式早于JPA。

当使用JPA引导时,Hibernate将按照JPA规范运行。

这两种模式之间存在一些差异:

有关这些差异的更多详细信息,请查看JpaCompliance课程。


1
public class HibernateSessionFactory {

private static final SessionFactory sessionFactory = buildSessionFactory1();

private static SessionFactory buildSessionFactory1() {
Configuration configuration = new Configuration().configure(); // configuration
                                                                // settings
                                                                // from
                                                                // hibernate.cfg.xml

StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder();


serviceRegistryBuilder.applySettings(configuration.getProperties());

ServiceRegistry serviceRegistry = serviceRegistryBuilder.build();

return configuration.buildSessionFactory(serviceRegistry);
}

public static SessionFactory getSessionFactory() {
return sessionFactory;
 }

public static void shutdown() {
// Close caches and connection pools
getSessionFactory().close();
 }

“ StandardServiceRegistryBuilder”也已弃用。
NixRam 2014年

StandardServiceRegistryBuilder不建议使用@NitinRam 。
JPG

在Hibernate中,如何进行过时和过时的转换很奇怪。曾经只有一点。stackoverflow.com/questions/17911308/...
NixRam

0

public void sampleConnection()引发异常{

     Configuration cfg = new Configuration().addResource("hibernate.cfg.xml").configure();
     StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
     SessionFactory sessionFactory = configuration.buildSessionFactory(ssrb.build());
     Session session = sessionFactory.openSession();
     logger.debug(" connection with the database created successfuly.");
}

0

我在上面编辑了batbaatar创建的方法因此它接受Configuration对象作为参数:

    public static SessionFactory createSessionFactory(Configuration configuration) {
        serviceRegistry = new StandardServiceRegistryBuilder().applySettings(
                configuration.getProperties()).build();
        factory = configuration.buildSessionFactory(serviceRegistry);
        return factory;
    }

在主班我做了:

    private static SessionFactory factory;
    private static Configuration configuration 
    ...      
    configuration = new Configuration();
    configuration.configure().addAnnotatedClass(Employee.class);
    // Other configurations, then           
    factory = createSessionFactory(configuration);

0

Hibernate 4.2.2中

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class Test {
    public static void main(String[] args) throws Exception
{
    Configuration configuration = new Configuration()
            .configure();

    ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(
            configuration.getProperties()).buildServiceRegistry();

    SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);

    Session session = sessionFactory.openSession();

    Transaction transaction = session.beginTransaction();

    Users users = new Users();

    ... ...

    session.save(users);

    transaction.commit();

    session.close();

    sessionFactory.close();

    }
}

0
Tested on 4.2.7 release

package com.national.software.hibernate;

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

import com.national.software.dto.UserDetails;

public class HibernateTest {

    static SessionFactory sessionFactory;

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        UserDetails user = new UserDetails();
        user.setUserId(1);
        user.setUserName("user1");

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

        ServiceRegistry  serviceRegistry = (ServiceRegistry) new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
        sessionFactory = config.buildSessionFactory(serviceRegistry);

        Session session = sessionFactory.openSession();
        session.beginTransaction();
        session.save(user);
        session.getTransaction().commit();

    }

}

0

这是休眠核心框架中不推荐使用的许多API。

我们创建了如下会话工厂:

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

从休眠4版本开始不推荐使用buildSessionFactory方法,并用新的API代替。如果您使用的是Hibernate 4.3.0及更高版本,则您的代码必须为:

  1. 配置配置= new Configuration()。configure();

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

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

从4.3.0开始,将ServiceRegistryBuilder类替换为StandardServiceRegistryBuilder。看起来5.0版本中将会有很多更改。对于已弃用的API以及使用的合适替代方案,仍然没有太多的说明。每个增量版本都提供了更不推荐使用的API,它们是通过微调版本5.0的核心框架来实现的。


0

在中hibernate 5.3.1,您可以尝试以下操作:

ServiceRegistry standardRegistry = 
                new StandardServiceRegistryBuilder().configure().build();

Metadata sources = new MetadataSources(standardRegistry).addAnnotatedClass(MyEntity.class).getMetadataBuilder().build();

SessionFactory sf = sources.buildSessionFactory();

0

如果有人在更新到5.1之后在这里,它是如何工作的

StandardServiceRegistry registry = new StandardServiceRegistryBuilder().configure().build();
                MetadataSources sources = new MetadataSources(registry);
                Metadata metadata = sources.getMetadataBuilder().build();
                sessionFactory = metadata.getSessionFactoryBuilder().build();

而不是下面的休眠4.3

 ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(
            configuration.getProperties()). buildServiceRegistry();
    sessionFactory = configuration.buildSessionFactory(serviceRegistry);

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.