Spring 整合 Hibernate 整合什麼 ?
1). 有 IOC 容器來管理 Hibernate 的 SessionFactory
2). 讓 Hibernate 使用上 Spring 的聲明式事務
Hibernate配置文件(相比於單獨的Hibernate配置減少一部分)
數據源需配置到 IOC 容器中, 所以在此處不再需要配置數據源.
關聯的 .hbm.xml 也在 IOC 容器配置 SessionFactory 實例時在進行配置
只需要配置方言,生成表的策略等.
Hibernate主配置
<session-factory> <property name="hibernate.dialect"> org.hibernate.dialect.MySQL5InnoDBDialect</property> <property name="hibernate.show_sql">true</property> <property name="hibernate.format_sql">true</property> <property name="hibernate.hbm2ddl.auto">update</property> <!-- 配置 hibernate 二級緩存相關的屬性. --> </session-factory>
Spring的IOC容器配置
<!-- 配置自動掃描的包 --> <context:component-scan base-package="com.atguigu.spring.hibernate"></context:component-scan> <!-- 一. 配置數據源 --> <!-- 導入資源文件 --> <context:property-placeholder location="classpath:db.properties"/> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="user" value="${jdbc.user}"></property> <property name="password" value="${jdbc.password}"></property> <property name="driverClass" value="${jdbc.driverClass}"></property> <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property> <property name="initialPoolSize" value="${jdbc.initPoolSize}"></property> <property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property> </bean> <!--二. 配置 Hibernate 的 SessionFactory 實例: 通過 Spring 提供的 LocalSessionFactoryBean 進行配置 有三個屬性--> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <!--1. 配置數據源屬性 --> <property name="dataSource" ref="dataSource"></property> <!--2. 配置 hibernate 配置文件的位置及名稱 --> <!-- <property name="configLocation" value="classpath:hibernate.cfg.xml"></property> --> <!--3. 配置 hibernate 映射文件的位置及名稱, 可以使用通配符 --> <property name="mappingLocations" value="classpath:com/atguigu/spring/hibernate/entities/*.hbm.xml"></property> <!-- 也可以使用 hibernateProperties 屬相來配置 Hibernate 原生的屬性 <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect </prop> <prop key="hibernate.show_sql">true</prop> <prop key="hibernate.format_sql">true</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> </props> </property>--> </bean> <!--三. 用XML配置 Spring 的聲明式事務 --> <!-- 1. 配置事務管理器 --> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <!-- 2. 配置事務屬性, 需要事務管理器 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="get*" read-only="true"/> <tx:method name="purchase" propagation="REQUIRES_NEW"/> <tx:method name="*"/> </tx:attributes> </tx:advice> <!-- 3. 配置事務切點, 並把切點和事務屬性關聯起來 --> <aop:config> <aop:pointcut expression="execution(* com.atguigu.spring.hibernate.service.*.*(..))" id="txPointcut"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/> </aop:config> </beans>