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:如果有事务加入,那么以非事务的方式运行

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值