Spring and hibernate framework integration

Integration key points:

1. The data source dataSource is handed over to Spring

  <!--Load properties file-->    
    <context:property-placeholder location="classpath:db.properties"/>
    <!-- Data source configuration -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driverClass}"></property>
        <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
        <property name="user" value="${jdbc.user}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>

2. The object of sessionFactory is handed over to spring

<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean" >
        <property name="dataSource" ref="dataSource"></property>
        <property name="configLocations" value="classpath:applicationContext.xml"></property>
</bean>

3. Transaction management

  (1) Configure the platformTransationManager interface (the underlying interface)

    Two implementation classes of platformTransationManager:

    jdbc technology: DataSourceTransationManager (this needs to configure dataSource)

    Hibernate technology: HibernateTransationManager (this needs to configure sessionFactory) (this time use this)

        These two transaction managers are explained in detail later 

  (2) Configure the transaction manager

    <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>

  (3) Management affairs

  Method 1: Manage transactions in xml

    1. Configure notifications

<!-- Specific enhancement logic--> 
<tx:advice id= " txAdvice " > <tx:attributes>
       <!-- matches method names in business classes --> <tx:method name="save*"/> <tx:method name="update*"/> <tx:method name="delete*"/> <tx:method name="find*" read-only="true"/> <tx:method name="*" /> </tx:attributes> </tx:advice>

   2. Configure aop aspect

<aop:config>
        <!-- Which methods of configuring the pointcut configuration need to be enhanced-->
        <aop:pointcut expression="execution(* cn.itcast.service.*.*(..))" id="cut"/>
        <!-- Configure aspect: apply enhanced logic to pointcut (notification + pointcut) -->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="cut"/>
    </aop:config>

  Method 2: Manage transactions by annotation

  1. Configure the transaction manager as above

  2. Start annotating the driver (scanning)

<tx:annotation-driven  transaction-manager="transactionManager"/>

  3. Use annotations on service classes or methods

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325260153&siteId=291194637