Question

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:

@Autowired
private SessionFactory sessionFactory;

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

sessionFactory.getCurrentSession().save() 
// 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]:

From HomeController.java:

@Controller public class HomeController {

@Autowired
private SessionFactory sessionFactory;
//Correlations Insert Handler
//DOCUMENT CREATE
@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";

}
//DOCUMENT READ
@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;
}

From DocumentControl.java:

public class DocumentControl {

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

        //READ
        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;
        }
    }

hibernate.cfg.xml:

hibernate-configuration>
    <session-factory>
        <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"/>
    </session-factory>
</hibernate-configuration>

persistence-context.xml:

    <bean id="dataSource"
        class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <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>
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation" value="classpath:hibernate.cfg.xml" />
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>             
                <prop key="hibernate.show_sql">true</prop>              
                <prop key=" hibernate.use_sql_comments">true</prop>     

            </props>
        </property>
    </bean>
    <bean id="transactionManager"
        class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <

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

Pas de solution correcte

Autres conseils

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top