220

When I updated the Hibernate version from 3.6.8 to 4.0.0, I got a warning about deprecated method buildSessionFactory() in this line:

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

the Javadoc recommends using another method

buildSessionFactory(ServiceRegistry serviceRegistry)

but in the documentation I found deprecated variant :(

Can you help me with this little misunderstanding?

Vlad Mihalcea
  • 103,297
  • 39
  • 432
  • 788
pushistic
  • 3,368
  • 3
  • 19
  • 35
  • Even in 4.3.8 quick start guide they are using this example: new Configuration() .configure().buildSessionFactory(); :( – Venkata Raju Mar 18 '15 at 09:40
  • @VenkataRaju May be, it is not bad, because of in Hibernate 5 everything turn back and this example correct, but (!) all configuration examples here are [not valid for Hibernate 5](http://stackoverflow.com/a/32711654/3405171). – v.ladynev Jan 16 '16 at 23:25

18 Answers18

382

Yes it is deprecated. Replace your SessionFactory with the following:

In 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;
}

UPDATE:

In Hibernate 4.3 ServiceRegistryBuilder is deprecated. Use the following instead.

serviceRegistry = new StandardServiceRegistryBuilder().applySettings(
            configuration.getProperties()).build();
Mark W
  • 5,416
  • 13
  • 52
  • 90
batbaatar
  • 5,370
  • 2
  • 16
  • 25
  • 6
    org.hibernate.service.ServiceRegistryBuilder is also depracated! – Accollativo Jan 15 '14 at 15:36
  • 12
    Yes, it seems ServiceRegistryBuilder is itself deprecated, looking at the documentation, they suggest using StandardServiceRegistryBuilder instead. So I guess the call should now be new StandardRegistryBuilder().applySettings(configuration.getProperties()).build(); – Simon B Jan 21 '14 at 08:31
  • I can't find StandardRegistryBuilder in hibernate 4.3 could it be that it was changed there? – Dejell Feb 19 '14 at 17:21
  • 7
    Instead of build() one needs buildServiceRegistry(), right? I can't find ServiceRegistry.build(). – Herbert Mar 03 '14 at 10:35
  • 46
    It seems its the mission of the hibernate team to deprecate everything they create. – 3urdoch Apr 23 '14 at 16:53
  • **Configuration configuration = new Configuration(); configuration.configure(); ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings( configuration.getProperties()).build(); return configuration.buildSessionFactory(serviceRegistry);** generates java.lang.ClassNotFoundException: javax.validation.ParameterNameProvider – gstackoverflow Jul 09 '14 at 11:43
  • @gstackoverflow `SessionFactory sessionFactory; ServiceRegistry serviceRegistry; Configuration config = new Configuration(); … sessionFactory = config.buildSessionFactory(serviceRegistry); serviceRegistry = new ServiceRegistryBuilder().applySettings( config.getProperties()).buildServiceRegistry();` Worked for me – kevingreen Jul 11 '14 at 17:16
  • 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(); – Pratap A.K Mar 14 '15 at 06:57
  • THANK YOU! The code suggested in the Hibernate 4.2 Tutorial actually uses StandardServiceRegistryBuilder, which is not included in any version of hibernate-core before v 4.3. Your code snippet was very useful. – PMorganCA Mar 18 '15 at 14:08
  • Please use hibernate 4.3 for StandardStandardServiceRegistryBuilder class – Ajay Sharma Aug 03 '15 at 09:48
  • It worked well for me, I am using Hibernate 4.3.1, Thank you :-) – Sachidananda Naik Mar 11 '16 at 17:41
16

Yes, it is deprecated. http://docs.jboss.org/hibernate/core/4.0/javadocs/org/hibernate/cfg/Configuration.html#buildSessionFactory() specifically tells you to use the other method you found instead (buildSessionFactory(ServiceRegistry serviceRegistry)) - so use it.

The documentation is copied over from release to release, and likely just hasn't been updated yet (they don't rewrite the manual with every release) - so trust the Javadocs.

The specifics of this change can be viewed at:

Some additional references:

ziesemer
  • 26,239
  • 8
  • 80
  • 90
7

or

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();

    }
}
Aboutblank
  • 687
  • 2
  • 14
  • 31
mixturez
  • 121
  • 2
  • 4
6

Code verified to work in Hibernate 4.3.0. Notice you can remove the XML filename parameter, or else provide your own path there. This is similar to (but typos corrected) other posts here, but this one is correct.

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);
MADHAIYAN M
  • 1,938
  • 21
  • 21
4

A better way to create SessionFactory object in Latest hibernate release 4.3.0 onward is as follow:

Configuration configuration = new Configuration().configure();
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().
applySettings(configuration.getProperties());
SessionFactory factory = configuration.buildSessionFactory(builder.build());
kavi temre
  • 1,241
  • 2
  • 13
  • 21
  • getting error: The method buildSessionFactory() in the type Configuration is not applicable for the arguments (StandardServiceRegistry) – Anju Sep 08 '16 at 10:22
4

It's as simple as this: the JBoss docs are not 100% perfectly well-maintained. Go with what the JavaDoc says: buildSessionFactory(ServiceRegistry serviceRegistry).

Matt Ball
  • 332,322
  • 92
  • 617
  • 683
4

It is not unusual to find discrepancies between different versions of documentation. Most developers view documentation as a chore, and they tend to put it off.

As a rule of thumb, if the javadoc says one thing and some non-javadoc documentation contradicts it, the chances are that the javadoc is more accurate. Programmers are more likely to keep the javadoc up to date with changes to the code ... because the "source" for the javadoc is in the same file as the code.

In the case of @deprecated tags, it is a virtual certainty that the javadoc is more accurate. Developers deprecate things after careful consideration ... and (generally speaking) they don't undeprecate them.

Stephen C
  • 632,615
  • 86
  • 730
  • 1,096
  • 1
    *...and they don't undeprecate them.* ... unless it's called `System.getenv(String)` http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4199068 – bestsss Dec 26 '11 at 03:00
  • 1
    It's not unusual to find crap projects, whose lazy developers don't bother about keeping the documentation aligned with the code, so that they drive their users crazy, while these try to figure out how the bloody rubbish works by rummaging in itself and hoping there is something more than /** TODO: comment-me */ :-\ – zakmck May 14 '12 at 15:42
  • @bestsss ...or it's called `Configuration.buildSessionFactory()` ;) – v.ladynev Jan 16 '16 at 23:13
2

If you are using Hibernate 5.2 and above then you can use this:

  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);
    }
  }
Hasan K
  • 540
  • 7
  • 18
2

TL;DR

Yes, it is. There are better ways to bootstrap Hibernate, like the following ones.

Hibernate-native bootstrap

The legacy Configuration object is less powerful than using the BootstrapServiceRegistryBuilder, introduced since Hibernate 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 bootstrap

You can also bootstrap Hibernate using JPA:

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();

This way, you are building the EntityManagerFactory instead of a SessionFactory. However, the SessionFactory extends the EntityManagerFactory, so the actual object that's built is aSessionFactoryImpl` too.

Conclusion

These two bootstrapping methods affect Hibernate behavior. When using the native bootstrap, Hibernate behaves in the legacy mode, which predates JPA.

When bootstrapping using JPA, Hibernate will behave according to the JPA specification.

There are several differences between these two modes:

For more details about these differences, check out the JpaCompliance class.

Vlad Mihalcea
  • 103,297
  • 39
  • 432
  • 788
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();
 }
Bharathiraja
  • 1,771
  • 17
  • 19
  • 'StandardServiceRegistryBuilder' is also deprecated. – NixRam Jul 16 '14 at 06:05
  • @NitinRam `StandardServiceRegistryBuilder` is NOT deprecated. – JPG Mar 03 '15 at 02:04
  • Quite weird how things are taken on and off deprecation in Hibernate. It used to be at one point. http://stackoverflow.com/questions/17911308/looking-for-a-not-deprecated-session-factory – NixRam Mar 03 '15 at 05:17
1

If anyone here after updating to 5.1 this is how it works

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

instead of the below in hibernate 4.3

 ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(
            configuration.getProperties()). buildServiceRegistry();
    sessionFactory = configuration.buildSessionFactory(serviceRegistry);
Lilac
  • 350
  • 1
  • 6
  • 22
0

public void sampleConnection() throws Exception {

     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.");
}
Creditto
  • 1,563
  • 2
  • 11
  • 17
0

I edited the method created by batbaatar above so it accepts the Configuration object as a parameter:

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

In the main class I did:

    private static SessionFactory factory;
    private static Configuration configuration 
    ...      
    configuration = new Configuration();
    configuration.configure().addAnnotatedClass(Employee.class);
    // Other configurations, then           
    factory = createSessionFactory(configuration);
Community
  • 1
  • 1
Nadjib Mami
  • 5,105
  • 9
  • 33
  • 48
0

In 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();

    }
}
saneryee
  • 2,635
  • 25
  • 20
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();

    }

}
Pratap A.K
  • 3,816
  • 6
  • 36
  • 72
0

here are many APIs deprecated in the hibernate core framework.

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. If you are using the hibernate 4.3.0 and above, your code has to be:

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

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

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

Class ServiceRegistryBuilder is replaced by StandardServiceRegistryBuilder from 4.3.0. It looks like there will be lot of changes in the 5.0 release. Still there is not much clarity on the deprecated APIs and the suitable alternatives to use. Every incremental release comes up with more deprecated API, they are in way of fine tuning the core framework for the release 5.0.

Creditto
  • 1,563
  • 2
  • 11
  • 17
0

In hibernate 5.3.1, you can try this:

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

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

SessionFactory sf = sources.buildSessionFactory();
Quan VO
  • 1,070
  • 9
  • 17
-1

Just import following package,

import org.hibernate.cfg.Configuration;
Prasad Bhosale
  • 633
  • 8
  • 18