Best way to provide Sessions for DAO's

1

I was searching the internet for ways to inject Sessions into DAO's this:

  

HibernateUtil

This form is about implementing a utility class that will configure, instantiate, and make available a org.hibernate.SessionFactory object that can be used globally (throughout the application).

Base code:

public class HibernateUtil {

    private static final SessionFactory SESSION_FACTORY = buildSessionFactory();

    public HibernateUtil() {
        super();
    }

    private static SessionFactory buildSessionFactory() {
        try {
            Configuration configuration = new Configuration().configure();
            StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
                    .applySettings(configuration.getProperties());

            return configuration.buildSessionFactory(builder.build());

        } catch (Throwable erro) {
            System.out
                    .println("Criação inicial do objeto Sessionfactory falhou. Erro: "
                            + erro);
            throw new ExceptionInInitializerError(erro);
        }
    }
  

Questions

1 - Spring Use, then Spring already gives me the SessionFactory instance according to the configuration I put in the Spring configuration file. And create a class with a property of type SessionFactory that will be injected and a method to make it available seems unnecessary. What is the best way to make Sessions available to DAOs using Spring? Maybe using AspectJ?

    
asked by anonymous 09.07.2014 / 05:21

1 answer

1

Without a shadow of a doubt, use Spring . Do not use these "utilitarian classes" that you see a lot around in projects that go into production. You can even use these classes in tests, and some quick temporary applications. But it is a bad practice to use them in larger projects.

Spring offers a very wide range of classes and APIs to integrate your application with various frameworks and libraries. Even Hibernate or JPA itself. It would reinvent the wheel in a Spring project using utilitarian class.

I will not go into detail on how to do this integration because I do not think it is the scope of your question. But I'll leave some links that can guide you in this integration if you have any difficulties. Logically, you can go back here in stackoverflow and ask your questions about this integration. Here are the links:

17.07.2014 / 01:35