In my app I've been passing my SessionFatory in my method parameters when I need to access my database within those methods. It's instantiated in my Controller using:

private SessionFactory sessionFactory;

And when I need to access my database I use lines like this:

// or
List products = sessionFactory.getCurrentSession().createSQLQuery("SELECT * FROM PRODUCTS").list();

Should I be creating new sessionFactories to get my current session or should is it okay to pass it as a parameter?

edit [added for clarity]:


@Controller public class HomeController {

private SessionFactory sessionFactory;
//Correlations Insert Handler
@RequestMapping(value="/documents", method = RequestMethod.PUT)
public @ResponseBody String insertDocument(HttpServletRequest request, HttpServletResponse response){       

    DocumentControl documentControl = new DocumentControl();
    documentControl.insertDocument(request, response, sessionFactory);
    return "went through just find";

@RequestMapping(value="/documents", method = RequestMethod.GET)
public @ResponseBody List<Documents> getAllDocuments(){
    //List documents = sessionFactory.getCurrentSession().createQuery("from Documents").list();         
    DocumentControl documentControl = new DocumentControl();
    List documents = documentControl.getAllDocuments(sessionFactory);
    return documents;


public class DocumentControl {

        private static Logger logger = Logger.getLogger(DocumentControl.class.getName());
        public DocumentControl(){};
        public void insertDocument(HttpServletRequest request, HttpServletResponse response, SessionFactory sessionFactory){
    Documents document = new Documents(request)

        public List<DocumentReturn> getAllDocuments(SessionFactory sessionFactory){
            List documents = sessionFactory.getCurrentSession().createQuery("from Documents").list();

            return documents;

        private boolean ifProductExists (String productCode, SessionFactory sessionFactory) {
            boolean exists = false;

            List<Products> productList = sessionFactory.getCurrentSession().createCriteria(Products.class).add( Restrictions.eq("productCode", productCode)).list();

            if ( !productList.isEmpty()  && productList.size() > 0 ) {
                exists = true;

            return exists;

        private boolean ifStandardExists (String standardCode, SessionFactory sessionFactory) {
            boolean exists = false;

            List<Standards> standardList = sessionFactory.getCurrentSession().createCriteria(Standards.class).add( Restrictions.eq("standardCode", standardCode)).list();

            if ( !standardList.isEmpty()  && standardList.size() > 0 ) {
                exists = true;

            return exists;


        <property name="hibernate.c3p0.acquire_increment">1</property>
        <property name="hibernate.c3p0.idle_test_period">100</property>
        <property name="hibernate.c3p0.max_size">10</property>
        <property name="hibernate.c3p0.max_statements">10</property>
        <property name="hibernate.c3p0.min_size">10</property>
        <property name="hibernate.c3p0.timeout">100</property>      
        <mapping class="***.*****.********.model.Documents"/>


    <bean id="dataSource"
        <property name="driverClassName" value="${jdbc.driverClassName}" />
        <property name="url" value="${jdbc.url}" />     
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
    <bean id="sessionFactory"
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation" value="classpath:hibernate.cfg.xml" />
        <property name="hibernateProperties">
                <prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>             
                <prop key="hibernate.show_sql">true</prop>              
                <prop key=" hibernate.use_sql_comments">true</prop>     

    <bean id="transactionManager"

property name="sessionFactory" ref="sessionFactory" />

No hay solución correcta

Otros consejos

SessionFactory is a Singleton. Therefore, you should get it from the ApplicationContext (i.e. using the @Autowired annotation). Passing it as a parameter will only complicate your API.

I think that you should leave creation of SessionFactory to the framework you are using and inject it as a resource just as you are doing by now. Besides you are not creating it in your code at all. Good practice is to create separate session for every chunk of data manipulation, if it is not done by a framework ofc. Session should be your main unit of work.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top