spring框架学习之路(二)-进阶技能(1)-数据库连接池和事务管理

1.定义Spring的数据库连接池

  <context:property-placeholder location="classpath:db.properties"/>  
  <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
     <property name="driverClass" value="${db_driver}"></property>
     <property name="jdbcUrl" value="${db_url}"></property>
     <property name="user" value="${db_username}"></property>
     <property name="initialPoolSize" value="${db_init_connections}"></property>
     <property name="maxPoolSize" value="${db_max_connection}"></property>
     <property name="password" value="${db_password}"></property>
  </bean> 
  <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
     <property name="dataSource" ref="dataSource"></property>
  </bean>

——–在其中db.properties文件中配置数据库的链接信息, (注意导入响应的数据库驱动包以及c3p0包)
JdbcTemplate类相当于一个BaseDao的代理类

db.properties文件格式:db_driver=com.mysql.jdbc.Driver
db_url=jdbc:mysql://localhost/test
db_init_connections=30
db_max_connection=60
db_username=root
db_password=123

在main方法中直接getBean获取JdbcTemplate类对象,即可使用!
**

2.spring事务的处理

首先声明事务管理器

<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"></property>
  </bean>

1)基于注解
—-在目标方法上添加注解

@Transactional[(propagation=Propagation.REQUIRED,readOnly=true,timeout=20000)]

—-让事务声明注解生效

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

2)基于XML文件
不需要添加注解

 <tx:advice id="transactionAdvice" transaction-manager="transactionManager">
     <tx:attributes>
<tx:method name="buss*" propagation="REQUIRED"/>
            <tx:method name="add*" propagation="REQUIRED"/>
            <tx:method name="update*" propagation="REQUIRED"/>
            <tx:method name="insert*" propagation="REQUIRED"/>
            <tx:method name="find" propagation="REQUIRED"/>
</tx:attributes>
  </tx:advice>   
  <aop:config>
     <aop:pointcut expression="execution(* com.neusoft..*(..))" id="txPoint"/>
     <aop:advisor advice-ref="transactionAdvice" pointcut-ref="txPoint"/>
  </aop:config>

附录:
propagation事务传播
1)REQUIRED_NEW:生成新的事务,如果存在之前的事务,之前的事务挂起
2)REQUIRED:如果当前存在事务,就是加入,如果没有创建
3)SUPPORTS:如果有事务加入,那么以非事务的方式运行

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章