java 如何在我的班级中使用 spring 和 hibernate 来获取会话工厂

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10070532/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 23:28:37  来源:igfitidea点击:

How can get the session factory in my class using spring with hibernate

javaspringhibernate

提问by Rafeek Muhammed

Here i am facing a problem that , i configured the hibernate sessionfactory in application.xml file and after how can i get the sessionFactory in my HibDao class (user defined class) for enabling user friendliness like begin(),commit(),rollback() with extending HibernateDaoSupport class..

在这里,我面临一个问题,我在 application.xml 文件中配置了 hibernate sessionfactory,之后如何在我的 HibDao 类(用户定义的类)中获取 sessionFactory 以启用用户友好性,如 begin()、commit()、rollback( ) 与扩展 HibernateDaoSupport 类..

Here is my application-hibernate.xml file :

这是我的 application-hibernate.xml 文件:

  <beans>   

<bean id="sessionFactory"       class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">     
    <property name="configLocation" value="/WEB-INF/hibernate.cfg.xml" />
</bean>



<!-- Transaction manager for a single Hibernate SessionFactory (alternative 
    to JTA) -->
<bean id="transactionManager"
    class="org.springframework.orm.hibernate3.HibernateTransactionManager">
    <property name="sessionFactory">
        <ref local="sessionFactory" />
    </property>
</bean>


<!-- ========================= BUSINESS OBJECT DEFINITIONS ========================= -->

<!-- Data access object: Hibernate implementation. -->

<bean id="HibernateSpringDaoTarget" class="com.netprofit.dao.HibernateSpringDAOImpl">
    <property name="sessionFactory">
        <ref local="sessionFactory" />
    </property>
</bean>

<!-- - Transactional proxy for Application's central data access object. 
    - - Defines specific transaction attributes with "readOnly" markers, - which 
    is an optimization that is particularly valuable with Hibernate - (to suppress 
    unnecessary flush attempts for read-only operations). - - Note that in a 
    real-life app with multiple transaction proxies, - you will probably want 
    to use parent and child bean definitions - as described in the manual, to 
    reduce duplication. -->

<bean id="SpringHibernateDao"
    class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
    <property name="transactionManager">
        <ref local="transactionManager" />
    </property>
    <property name="target">
        <ref local="HibernateSpringDaoTarget" />
    </property>
    <property name="transactionAttributes">
        <props>
            <prop key="get*">PROPAGATION_REQUIRED,readOnly</prop>
            <prop key="find*">PROPAGATION_REQUIRED,readOnly</prop>
            <prop key="load*">PROPAGATION_REQUIRED,readOnly</prop>
            <prop key="store*">PROPAGATION_REQUIRED</prop>
            <prop key="add*">PROPAGATION_REQUIRED</prop>
        </props>
    </property>
</bean>

Here is the hibernate-cfg.xml file :

这是 hibernate-cfg.xml 文件:

          <?xml version="1.0" encoding="UTF-8"?>
         <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
     <hibernate-configuration>
<session-factory>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/netprofit</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">test</property>
    <property name="hibernate.connection.autocommit">false</property>
    <property name="hibernate.hbm2ddl.auto">update</property>
    <property name="hibernate.show_sql">true</property>
    <property name="hibernate.format_sql">true</property>
    <property name="hibernate.jdbc.batch_size">50</property>


    <property name="hibernate.c3p0.max_size">1</property>
    <property name="hibernate.c3p0.min_size">0</property>
    <property name="hibernate.c3p0.timeout">5000</property>
    <property name="hibernate.c3p0.max_statements">1000</property>

    <property name="hibernate.c3p0.idle_test_period">300</property>
    <property name="hibernate.c3p0.acquire_increment">1</property>


    <mapping class="com.netprofit.dao.hibernate.HUserRegistrationPojo" />
</session-factory>

Here is the HibDao class (User defined class for simplicity) :

这是 HibDao 类(为简单起见,用户定义的类):

  public class HibDao extends HibernateDaoSupport {
private static final ThreadLocal THREAD = new ThreadLocal();

protected HibDao() {
}

public static Session session() throws Exception {
    Session session = (Session) HibDao.THREAD.get();
    if (session == null) {            
        session = getSessionFactory().openSession();  **--->>>Here how can i open the Session**
        HibDao.THREAD.set(session);
        session().setFlushMode(FlushMode.COMMIT);
    }
    return session;
}

protected static void begin() throws Exception {
    session().beginTransaction();

}

protected static void commit() throws Exception {
    session().getTransaction().commit();
}

protected static void rollback() throws Exception {
    session().getTransaction().rollback();
    session().close();
    HibDao.THREAD.set(null);
}

protected static void flush() throws Exception {
    session().flush();
}

protected static void close() throws Exception {

    session().close();
    HibDao.THREAD.set(null);
}
 }

And after that i just extend the HibDao class and use the begin(), commit() and rollback() method for handling hibernate transaction... and also i am not familiar with Spring......

之后我只是扩展了 HibDao 类并使用 begin()、commit() 和 rollback() 方法来处理休眠事务……而且我对 Spring 也不熟悉……

Thanks....

谢谢....

采纳答案by tusar

There is no specific question specified (without the comment line). I read the question like this - "I have injected the SessionFactory bean in xml file. Now, I want to recollect it in a Java program."

没有指定具体问题(没有注释行)。我读到这样的问题 - “我已经在 xml 文件中注入了 SessionFactory bean。现在,我想在 Java 程序中回忆它。”

Simple!

简单的!

ApplicationContext context = new FileSystemXmlApplicationContext("c:/../application-hibernate.xml");
SessionFactory sessionFact = (SessionFactory) context.getBean("sessionFactory");

Now you can do :

现在你可以这样做:

Session session =  sessionFact.openSession();    

Note : I am fetching the bean by directly parsing the xml file, it is not a good practise. In ideal cases you will be fetching ApplicationContext object from request object of Servlet/Action class.

注意:我通过直接解析 xml 文件来获取 bean,这不是一个好习惯。在理想情况下,您将从 Servlet/Action 类的请求对象中获取 ApplicationContext 对象。