java - 什么时候创建一个新的 SessionFactory?

标签 java spring hibernate

在我的应用程序中,当我需要在这些方法中访问我的数据库时,我一直在我的方法参数中传递我的 SessionFatory。它在我的 Controller 中实例化,使用:

@Autowired
private SessionFactory sessionFactory;

当我需要访问我的数据库时,我使用这样的行:

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

我应该创建新的 sessionFactories 来获取我当前的 session 还是应该将它作为参数传递?

编辑[为清楚起见添加]:

来自 HomeController.java:

@ Controller 公共(public)类 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;
}

来自 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>

持久性上下文.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>

最佳答案

SessionFactory 是一个 Singleton .因此,您应该从 ApplicationContext 中获取它(即使用 @Autowired 注释)。将其作为参数传递只会使您的 API 复杂化。

关于java - 什么时候创建一个新的 SessionFactory?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22155328/

相关文章:

java - 在 Maven jar 构建中将 Class-Path 设置为 Rsrc-Class-Path

java - 如何在 Spring 框架中使用 Apache 的 MultiKeyMap

java - RMI 或 Servlets 通过防火墙向/从 applet 发送对象?

java - 每次我更改标签时标签 fragment 获取数据

java - 通过 Spring by Environment 注入(inject)属性值

java - Spring中具有多种角色的组件

java - 生成的序列以 1 开头,而不是在注释中设置的 1000

spring - 在 Spring Boot 中禁用所有与数据库相关的自动配置

java - 为什么我会收到 HTTP 状态 500 - 未知实体 : org. hibernate.impl.SessionImpl 异常?

Java 消息传递 : Difference between ActiveMQ, Mule、ServiceMix 和 Camel