Integration of spring and Hibernate

Source: Internet
Author: User

Spring provides great support for hibernate integration. Spring provides initialization for sessionfactory, So you no longer need to worry about session open and close. Spring also provides flexible transaction declarations.

This article describes how to integrate hibernate in Spring through examples.

1. Add the hibernate configuration to the spring configuration (configure datasource and sessionfactory ):

<bean id="dataSource"        class="org.springframework.jdbc.datasource.DriverManagerDataSource">        <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />        <property name="url" value="jdbc:oracle:thin:@localhost:1521:ORCL" />        <property name="username" value="user" />        <property name="password" value="pwd" />    </bean>    <bean id="mySessionFactory"        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">        <property name="dataSource" ref="dataSource" />        <property name="mappingResources">            <list>                <value>com/test/spring/hibernate/Hbtest.hbm.xml                </value>            </list>        </property>        <property name="hibernateProperties">            <value>                hibernate.dialect=org.hibernate.dialect.Oracle10gDialect                hibernate.show_sql=true                hibernate.format_sql=true                hibernate.current_session_context_class=thread            </value>        </property>    </bean>

The Hibernate configuration can also be separately placed in hibernate. cfg. in the XML file, and then point to the config file through the following configuration. In this way, do not configure datasource and other hibernate-related information in spring configuration.

    <bean id="mySessionFactory"        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">        <property name="configLocation" value="classpath:conf/Hibernate.cfg.xml" />    </bean>

2. Inject sessionfactory into Dao and use sessionfactory to operate the APIS provided by hibernate:

    <bean id="PlainHibernateDAO" class="com.test.spring.hibernate.PlainHibernateDAO">        <property name="sessionFactory" ref="mySessionFactory" />    </bean>

Application instance:

1. inherit the hibernatedaosupport or instantiate it by yourself.HibernatetemplateUseHibernateTemplate,HibernateTemplateThe current hibernate
SessionThe object is correctly opened and closed, and directly involved in transaction management. Do not allow users to open or close the session, and then directly callHibernateTemplateMethod provided.

public class DAOSupportDAO extends HibernateDaoSupport {    public void persist2(Hbtest transientInstance) {        log.debug("persisting Hbtest instance");        try {            this.getHibernateTemplate().save(transientInstance);            log.debug("persist successful");        } catch (RuntimeException re) {            log.error("persist failed", re);            throw re;        }    }...}

2. inherit the hibernatedaosupport
UseSessionfactory.

public class DAOSupportDAO extends HibernateDaoSupport {    private static final Log log = LogFactory.getLog(DAOSupportDAO.class);       public void persist(Hbtest transientInstance) {        log.debug("persisting Hbtest instance");        try {            this.getSessionFactory().getCurrentSession().save(transientInstance);            log.debug("persist successful");        } catch (RuntimeException re) {            log.error("persist failed", re);            throw re;        }    }

3. Inject sessionfactory (Recommended Practice: The advantage is that spring classes will not be introduced)

public class PlainHibernateDAO {    private static final Log log = LogFactory.getLog(PlainHibernateDAO.class);    private SessionFactory sessionFactory;    public void setSessionFactory(SessionFactory sessionFactory) {        this.sessionFactory = sessionFactory;    }    public void persist(Hbtest transientInstance) {        log.debug("persisting Hbtest instance");        try {            sessionFactory.getCurrentSession().save(transientInstance);            log.debug("persist successful");        } catch (RuntimeException re) {            log.error("persist failed", re);            throw re;        }    }

Manage transactions:

1. The sessionfactory. getcurrentsession (). begintransaction () and commit provided by hibernate are displayed.

Hibernate. current_session_context_class = thread must be configured for hibernateproperties.

        <property name="hibernateProperties">            <value>                hibernate.current_session_context_class=thread                               </value>

2. Use spring's transaction Declaration for management: hibernateproperties cannot be configured with hibernate. current_session_context_class = thread

 

<tx:advice id="txAdvice" transaction-manager="txManager">        <tx:attributes>            <tx:method name="*" propagation="REQUIRED"/>        </tx:attributes>    </tx:advice>    <bean id="txManager"        class="org.springframework.orm.hibernate3.HibernateTransactionManager">        <property name="sessionFactory" ref="mySessionFactory" />    </bean>    <aop:config>        <aop:pointcut id="persistOperation"            expression="execution(* com.test.spring.hibernate.PlainHibernateDAO.*(..))" />        <aop:advisor advice-ref="txAdvice" pointcut-ref="persistOperation" />           </aop:config>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.