Spring整合Hibernate
配置数据库连接池
<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
同时将SessionFactory注入到Dao实现类和事务管理器中
<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事务管理
让Spring通过AOP来处理事务(横切关注功能)
<bean id="transactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<tx:annotation-driven />
tx:annotation-driven
<tx:annotation-driven/> 就是支持事务注解的(@Transactional)
default-autowire="byType
加入这个xml里面的bean依赖可以自动装配
配置事务切面
配置事务增强(包围型增强)定义切面执行的时机
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
配置切面通过切点表达式定义切面执行的位置
<aop:config>
<aop:advisor advice-ref="txAdvice"
pointcut="execution(* com.kygo.biz.impl.*.*(..))"/>
</aop:config>