Best Way to Provide Sessions for DAO’s

Asked

Viewed 117 times

1

I was researching on the internet ways to inject Sessions in the DAO’s this:

Hibernateutil

This way is to implement a utility class that will configure, instantiate and make available an object org.hibernate.SessionFactory which 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 provides me the instance of Sessionfactory according to the configuration I put in the Spring configuration file. And creating a class with a Sessionfactory-like property that will be injected and a method to make it available seems unnecessary. What is the best way to make Sessions available to DAO’s using Spring? Maybe, use Aspectj?

1 answer

1


Beyond the shadow of a doubt, use Spring. Don’t use these "utility classes" that you see around a lot in projects that go into production. You can even use these classes in tests, and some quick temporary applications. But it’s 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. Including Hibernate itself or JPA. It would reinvent the wheel in a Spring project using utility class.

I’m not going to go into detail on how to do this integration because I don’t think it’s the scope of your question. But I will leave some links that can guide you in this integration if you have any difficulties. Logically, you can come back here at stackoverflow and ask your questions regarding this integration. Here are the links:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.