Domanda

I'm currently re-learning Hibernate, which I haven't used for some five or six years, and I'm trying to think back to the ways we used to use it at an old workplace (Hibernate in Action is on order...)

I'm not using spring in my application at present, and one thing that I'm wondering is how to best retrieve the SessionFactory in my application to share it across my persistence helpers - I seem to recall that you generally only want to use one. In my current codebase I'm choosing to do so like this in a class common to all my peristence 'helpers':

public abstract class AbstractHelper {

  private static final String CONFIG = "configuration.xml";
  private static SessionFactory sessionFactory = null;

  /**
   * @return SessionFactory the Hibernate SessionFactory.
   */
  public static SessionFactory getSessionFactory() {
    if (sessionFactory == null) {
      Configuration configuration = new Configuration();
      configuration.configure(CONFIG);
      ServiceRegistryBuilder serviceRegistryBuilder = 
            new ServiceRegistryBuilder().applySettings(configuration.getProperties());
      sessionFactory = configuration.buildSessionFactory(
            serviceRegistryBuilder.buildServiceRegistry());
    }

    return sessionFactory;
  }

}

Does this even make sense to people, or should I be going about this in a different way for reasons of performance, etc?

È stato utile?

Soluzione

There is a small chance you can get in trouble when your code is accessed from multiple threads. When two threads access getSessionFactory() one might create a SessionFactory and the other one might reach if(sessionFactory == null) before the first one is assigned to the variable.

The easiest way to fix this is to make getSessionFactory() synchronized. This might cause some locking-overhead and have an impact on performance.

For more sophisticated methods see for example here or do some googling on "Singleton pattern java".

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top