Spring整合Hibernate
配置數(shù)據(jù)庫連接池
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/hib?useUnicode&characterEncoding=utf8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
<property name="initialSize" value="10" />
<property name="maxTotal" value="50" />
<property name="maxWaitMillis" value="10000" />
</bean>
配置sessionFactory
通過Spring的IoC容器來管理Hibernate的SessionFactory
同時(shí)將SessionFactory注入到Dao實(shí)現(xiàn)類和事務(wù)管理器中
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="annotatedClasses">
<list>
<value>com.kygo.entity.User</value>
</list>
</property>
<property name="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.show_sql=true
hibernate.format_sql=true
hibernate.hbm2ddl=update
</value>
</property>
</bean>
配置transactionManager事務(wù)管理
讓Spring通過AOP來處理事務(wù)(橫切關(guān)注功能)
<bean id="transactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<tx:annotation-driven />
tx:annotation-driven
<tx:annotation-driven/> 就是支持事務(wù)注解的(@Transactional)
default-autowire="byType
加入這個(gè)xml里面的bean依賴可以自動(dòng)裝配
配置事務(wù)切面
配置事務(wù)增強(qiáng)(包圍型增強(qiáng))定義切面執(zhí)行的時(shí)機(jī)
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
配置切面通過切點(diǎn)表達(dá)式定義切面執(zhí)行的位置
<aop:config>
<aop:advisor advice-ref="txAdvice"
pointcut="execution(* com.kygo.biz.impl.*.*(..))"/>
</aop:config>